Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign string to element in structure in C

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

like image 221
Kreuzade Avatar asked Aug 29 '12 14:08

Kreuzade


2 Answers

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.

like image 198
Keith Miller Avatar answered Nov 02 '22 14:11

Keith Miller


You can assign value to string only while declaring it. You can not assign it later by using =.

You have to use strcpy() function.

like image 27
Sachin Mhetre Avatar answered Nov 02 '22 12:11

Sachin Mhetre