I have a problem with assigning values to a string array which is a field in my struct. In this case, I am also using an array of this structs. When I assign values without for loop, everything works fine. But the problem occurs in the for loop. I have printed all assignments and they are OK. But the problem actually is, that the every assignment actually rewrites all array positions in all structures of that field.
struct ship
{
int length;
char *fields[4];
};
struct ship shipPositions[6];
for(int h=0; h < length; h++) //goes from 0 to 3 for first two values
{
char c = getCharFromInt(begin + h); //my function which works fine; begin = 2;
char coord[3] = "$";
append(coord, c); // also works fine
append(coord,ships[i][1]);
shipPositions[i].fields[h] = coord;
printf("shipPositions[%d].fields[%d] = %s\n", i,h,shipPositions[i].fields[h]);
}
printf("Position: %s\n",shipPositions[0].fields[0]);
printf("Position: %s\n",shipPositions[0].fields[1]);
/* it prints assignments and then on the first two values after for loop
shipPositions[0].fields[0] = $C2
shipPositions[0].fields[1] = $D2
shipPositions[0].fields[2] = $E2
shipPositions[1].fields[0] = $F0
shipPositions[1].fields[1] = $G0
shipPositions[1].fields[2] = $H0
shipPositions[5].fields[0] = $H8
shipPositions[5].fields[1] = $I8
Position: $I8
Position: $I8
*/
And when I simulate first two cases of for loop, everything is also fine:
char c1 = getCharFromInt(2 + 0);
char coord1[3] = "$";
append(coord1, c1);
append(coord1,ships[0][1]);
shipPositions[0].fields[0] = coord1;
printf("shipPositions[%d].fields[%d] = %s\n", 0,0,shipPositions[0].fields[0]);
char c2 = getCharFromInt(2 + 1);
char coord2[3] = "$";
append(coord2, c2);
append(coord2,ships[0][1]);
shipPositions[0].fields[1] = coord2;
printf("shipPositions[%d].fields[%d] = %s\n", 0,1,shipPositions[0].fields[1]);
printf("Position: %s\n",shipPositions[0].fields[0]);
printf("Position: %s\n",shipPositions[0].fields[1]);
/*
shipPositions[0].fields[0] = $C2
shipPositions[0].fields[1] = $D2
Position: $C2
Position: $D2
*/
struct Position { int x, y; }say.structinstead of a string for coordinates.