Assign string to element in structure in C

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.

Leave a Comment