I'm currently playing a bit with C and trying to understand strings. Can somebody please explain why this is working:
开发者_JS百科char test[] = "test";
And why the following does not?
char test[255];
test = "test";
Because this is an initialization:
char test[] = "test";
and this is an assignment:
test = "test";
and you cannot assign arrays in C (and strings in C are just arrays).
Your best bet is to copy the string using strcpy()
(or to be safe, strncpy()
).
C doesn't allow you to assign values to an entire array except when it's initialized.
The correct way to copy a string into an existing array is with strcpy
:
char test[255];
strcpy(test,"test");
even though what you say looks obvious,it is incorrect.you can't directly assign a string to a character array.you could try and use strcpy() function.
Because "test" is a pointer and test is an array. You can always use strcpy() though.
Unfortunately C doesnot support direct assigment of string(As it invloves more than 1 memory address). You must rather use strcpy or memcpy functions.
well yeah
test[0]='t' works (since your accessing one memory location at the time)
You can't assign an array directly because it is an unmodifiable lvalue. But you can use an indirectly assignment like:
typedef struct { char s[100]; } String;
int main()
{
char a[100] = "before";
assert( sizeof a >= sizeof(String) );
puts( a );
*(String*)a = *(String*) "after";
puts( a );
return 0;
}
精彩评论