繁体   English   中英

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

[英]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

第一个数字仅用于识别后面有多少个数字。 对于第一行,第一个打印语句将其读入为 0132011,但当执行第二个打印语句时,它会打印出 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");
    }

看起来像覆盖 memory 的问题,因为您没有在 malloc 调用中分配足够的空间。 Malloc 分配您要求的特定字节数。 您要求 (numRequests[i]+i) 个字节。 但是您实际上是在寻找指向 int 的 (numRequests[i]+i) 指针。

尝试类似的东西

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM