为什么我的数组中的这些整数值会发生变化?

Why are these integer values in my array changing?

我正在尝试从文件中读取数据,它似乎被正确读取,但是当我打印数据时,值的 2 变为 3。我很困惑为什么会这样。正在读入的文件如下所示:

约翰 7 0 1 3 2 0 1 1
杰克 3 4 4 1
简 5 3 2 3 0 4
珍妮 6 4 2 1 3 0 4
吉姆 2 0 0
乔安娜 4 1 2 4 2

第一个数字只是用来标识后面有多少个数字。对于第一行,第一个 print 语句将其读取为 0132011,但是当执行第二个 print 语句时,它打印出 0132441。这也发生在 Jenny 的行中。读入为 421304,但打印为 421300。

int* philRequests[numPhilosophers];
int numRequests[numPhilosophers];

    for(int i = 0; i < numPhilosophers; i++){
        fscanf(fp, "%s", buff);
        strcpy(names[i], buff);
        fscanf(fp, "%d", &numRequests[i]);
        philRequests[i] = (int *)malloc(numRequests[i] + 1);  //allocates memory by the number of requests each phil will make
        
        for(int x = 0; x < numRequests[i]; x++){
            fscanf(fp, "%d", &philRequests[i][x]);
            printf("\nAdding %d to %d %d", philRequests[i][x], i, x);
        }

    fgets(buff, 255, (FILE*)fp); //moves on to next line
    }

//displaying what was just read in
for(int i = 0; i < numPhilosophers; i++){
        for(int x = 0; x < numRequests[i]; x++){
            printf("\nReading %d from %d %d", philRequests[i][x], i , x);
        }
        printf("\n");
    }

覆盖内存似乎是一个问题,因为您没有在 malloc 调用中分配足够的 space。 Malloc 分配您要求的特定字节数。您要求 (numRequests[i]+i) 字节。但你实际上是在寻找 (numRequests[i]+i) 指向 int.

的指针

试试

philRequests[i] = malloc((numRequests[i] + 1)*sizeof(int*));