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?
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