Assigning a char pointer to char array in C

妖精的绣舞 提交于 2019-12-24 13:42:12

问题


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:


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;



回答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);
}



回答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.



来源:https://stackoverflow.com/questions/29575109/assigning-a-char-pointer-to-char-array-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!