I have this structure:
typedef struct SM_DB
{
LIST_TYPE link;
char name[SM_NAME_SIZE];
} SM_DB_TYPE;
And I would like to assign a string to its 'name'. I am doing so like this:
SM_DB_TYPE one;
one.name = "Alpha";
However, after compiling I get an error: "error C2106: '=' : left operand must be l-value". I am hoping this is fairly obvious. Does anyone know what I am doing wrong?
Thanks
Assuming SM_NAME_SIZE
is large enough you could just use strcpy
like so:
strcpy(one.name, "Alpha");
Just make sure your destination has enough space to hold the string before doing strcpy your you will get a buffer overflow.
If you want to play it safe you could do
if(!(one.name = malloc(strlen("Alpha") + 1))) //+1 is to make room for the NULL char that terminates C strings
{
//allocation failed
}
strcpy(one.name, "Alpha"); //note that '\0' is not included with Alpha, it is handled by strcpy
//do whatever with one.name
free(one.name) //release space previously allocated
Make sure you free one.name
if using malloc so that you don't waste memory.
You can assign value to string only while declaring it. You can not assign it later by using =
.
You have to use strcpy()
function.
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