here is a code sample
void something()
{
char c[100];
scanf("%s",c);
char c2[100]=c;
}
my problem is when i do this assignment an error says that i can't assign
char * "c" to char[] "c2";
how can i achieve this assignment?
You'll have to use strcpy()
(or similar):
...
char c2[100];
strcpy(c2, c);
You can't assign arrays using the =
operator.
Better practice would be to use strncpy(c2, c, 100) to avoid buffer overflow, and of course limit the data entry too with something like scanf("%99s", c);
strncpy
since it won't necessarily NUL-terminate. (Not a problem here since both c
and c2
have the same number of elements, but OTOH, that also means plain strcpy
wouldn't be a problem either.) 2. fgets
would be better than scanf
. c-faq.com/stdio/scanfprobs.html
Jan 15, 2010 at 20:17
char []
is not a valid value type in C (its only a valid declaration type), so you can't actualy do anything with char []
types. All you can do is convert them to something else (usually char *
) and do something with that.
So if you wany to actually do something with the data in the array, you need to use some function or operation that takes a char *
and derefences it. Obvious choices for your example are strcpy or memcpy
c
toc2
or are you wanting to assign the pointerc
toc2
?void
return type.