This has been bugging me for a while.
struct person {
char name[15];
int age;
};
struct person me;
me.name = "nikol";
when I compile I get this error:
error: incompatible types when assigning to type ‘char[15]’ from type ‘char *’
am I missing something obvious here?
The c_str() and strcpy() function in C++ C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0').
You can store a string in a char array of length 1, but it has to be empty: The terminating null character is the only thing that can be stored.
We can directly assign the address of 1st character of the string to a pointer to char. This should be the preferred method unless your logic needs a copy of the string.
Arrays are second-class citizens in C, they do not support assignment.
char x[] = "This is initialization, not assignment, thus ok.";
This does not work:
x = "Compilation-error here, tried to assign to an array.";
Use library-functions or manually copy every element for itself:
#include <string.h>
strcpy(x, "The library-solution to string-assignment.");
me.name = "nikol";
is wrong !! you need to use strcpy()
when you do x = "Some String"
, actually you are putting the starting address of the static string "Some String"
into variable x
. In your case, name
is a static array, and you cannot change the address. What you need, is to copy your string to the already allocated array name
. For that, use strcpy()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With