Assign string to element in structure in C

后端 未结 5 1650
别跟我提以往
别跟我提以往 2020-12-06 21:03

I have this structure:

typedef struct SM_DB
{
    LIST_TYPE           link;
    char                name[SM_NAME_SIZE];
} SM_DB_TYPE;

And I

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-06 21:33

    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.

提交回复
热议问题