Search code examples
cstringpointersreallocarrays

How do I properly assign pointers in string array in C?


I struggle with pointers in C. I need to put first element of each line into an array.

Important parts :

char shipname[10];
char **shipTable = NULL;


 while ( fgets( line,100,myfile) != NULL ) {
     sscanf(line, "%s %lf %lf %lf %lf", shipname, &lat, &lng, &dir, &speed);
     shipTable = realloc( shipTable, numofShips*sizeof(char*) );
     shipTable[numofShips-1]=malloc((10)*sizeof(char));
     (shipTable)[numofShips-1] = shipname;
     //char *shipname=malloc((10)*sizeof(char));
     numofShips++;
     }

And when I print my shipTable out every element is the same, i have tried every combination of & and * i came up to.


Solution

  • You are assigning a pointer value to each element of shiptTable - namely, a pointer to the first element of shipname, whose location in memory never changes. What you actually want to do is copy the string each time - e.g. strcpy(shiptable[numofShips-1], shipname).

    Or even better, just allocate the memory before sscanf, and use shiptable[numofShips-1] as the argument in sscanf, instead of shipname.