3

I am starting to studying C and I already run into few problems. I want to parse a file and store the results of each line in a structure. My structure looks like:

struct record {
    char x[100];
}

Then, whenever I use strtok to parse a line in some file.txt,

struct record R;
...
char *token;
token = strtok(line, "\t");

token returns a pointer to the string and whenever I print it, it is correct string. I want to assign token to x, such as R.x = token, but I get an error, "char x[100] is not assignable". Is it possible to convert this pointer token to actual char array or what would be the best way to store the results into the structure?

1
  • You cannot assign arrays like that. Use memcpy() to fill it with the data you want it to contain. Commented Apr 11, 2015 at 7:07

3 Answers 3

5

The error says it all. Arrays are not assignable. You need to copy each character one by one and then append a NUL-terminator at the end.

Fortunately there is a function that does this for you. The name of the function is strcpy and it is found in the string.h header.

To fix your issue, use

strcpy(R.x,token);

instead of

R.x = token;
Sign up to request clarification or add additional context in comments.

Comments

1

Use strcpy after making sure that the string fits in the array:

#define LEN(array) (sizeof (array) / sizeof (array)[0])

if (strlen(token) < LEN(R.x)) {
   strcpy(R.x, token);
} else {
   fprintf(stderr, "error: input string \"%s\" is longer than maximum %d\n", token, LEN(R.x) - 1);
}

Comments

1

strcpy stops when it encounters a NULL, memcpy does not. So if you array have 0x00 eg. \0 in middle,you should use memcpy rather than strcpy.

Comments

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.