0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I just tried this 10 minutes ago, thanks for fast and accurate answer:D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.