0

So I have a snippet of code that reads a text file with 10 columns and 5 rows of number/letter pairs. I populate and read a 2d array e.g.

for (i = 0; i < 5; i++) {
    for (j = 0; j < 10; j++) {

        getdelim(&line, &len, ' ', fp);
        grid[i][j] = line;
        printf("%s ", grid[i][j]);

    }   

    printf("\n");
}

and the output is as expected as:

12 9F H2 FQ 0M CH RD XC W8 4D

VT C8 TM ZQ 0E PQ D1 2J YD KK

XY P5 AW 4Y 41 05 6E HW F2 QQ

YF R5 JV 4N 7F 4J V1 9K MM 0M

CT RF RM WV C6 V9 P6 TW WX MX

But if I re-read the elements of the array in another for loop:

for (i = 0; i < 5; i++) {
    for (j = 0; j < 10; j++) {

        printf("%s ", grid[i][j]);

    }   

    printf("\n");
}

I get the very last element in the array for every element in the array e.g.

MX MX MX MX MX MX MX MX MX MX
MX MX MX MX MX MX MX MX MX MX
MX MX MX MX MX MX MX MX MX MX
MX MX MX MX MX MX MX MX MX MX
MX MX MX MX MX MX MX MX MX MX

What gives?

4

2 回答 2

4

You need to provide the declarations for your array grid and line buffer.

Anyway, most likely you are referring to the same line buffer from each element of your array. When you "populate" your array in the first cycle, you only print the most recently initialized element, which creates an illusion of everything "working" properly. But when you actually try to re-verify the content of the array, the illusion falls apart.

Try printing some previously initialized elements in your first cycle, and you will see that your first cycle does not work either: all of the previously initialized array elements will seem to have the same value and that value will change at each iteration.

于 2012-08-24T00:35:38.907 回答
0

i'd say line is of type char* and every time you're writing to its address using getdelim, you're changing the value and not the reference ... in effect, all grid[i][j] are pointing to the same string, hence the resultant behavior

try malloc'ing and strcpy'ing to each grid[i][j] in the loop

grid[i][j] = (char*)malloc(3);
strcpy(grid[i][j], line);
于 2012-08-24T00:37:51.983 回答