Assigning a char pointer to char array in C
Solution 1
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;
Solution 2
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);
}
Solution 3
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
.
Related videos on Youtube
Sam
Updated on July 09, 2022Comments
-
Sam almost 2 years
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?-
Bregalad about 9 yearsYou cannot assign arrays like that. Use
memcpy()
to fill it with the data you want it to contain.
-