简体   繁体   English

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

[英]Why are these integer values in my array changing?

I'm trying to read in data from a file and it seems to be read in correctly, however when I print the data 2 of the values change to 3. I'm very confused why this is happening.我正在尝试从文件中读取数据,并且似乎已正确读取,但是当我打印数据时,值 2 变为 3。我很困惑为什么会这样。 The file that is being read in looks like this:正在读取的文件如下所示:

John 7 0 1 3 2 0 1 1约翰 7 0 1 3 2 0 1 1
Jack 3 4 4 1杰克 3 4 4 1
Jane 5 3 2 3 0 4简 5 3 2 3 0 4
Jenny 6 4 2 1 3 0 4珍妮 6 4 2 1 3 0 4
Jim 2 0 0吉姆 2 0 0
Joanna 4 1 2 4 2乔安娜 4 1 2 4 2

The first number is just used to identify how many following numbers there are.第一个数字仅用于识别后面有多少个数字。 For the first line, the first print statement reads it in as 0132011, but when the second print statement is executed it prints out 0132441. This also happens in the line with Jenny.对于第一行,第一个打印语句将其读入为 0132011,但当执行第二个打印语句时,它会打印出 0132441。这也发生在 Jenny 行中。 It is read in as 421304, but printed out as 421300.它读入为 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");
    }

Looks like an issue with overwriting memory because you aren't allocating enough space in your malloc call.看起来像覆盖 memory 的问题,因为您没有在 malloc 调用中分配足够的空间。 Malloc allocates the specific number of Bytes you ask for. Malloc 分配您要求的特定字节数。 You ask for (numRequests[i]+i) Bytes.您要求 (numRequests[i]+i) 个字节。 But you are actually looking for (numRequests[i]+i) pointers to int.但是您实际上是在寻找指向 int 的 (numRequests[i]+i) 指针。

Try something like尝试类似的东西

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

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

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