Assign string to element in structure in C

后端 未结 5 1641
别跟我提以往
别跟我提以往 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:40

    Use:

    strcpy(one.name, "Alpha"); //Removed null byte (Read first comment by shf301)
    

    Alternative:

    typedef struct SM_DB  
    {
        LIST_TYPE           link;
        char*               name;   
    } SM_DB_TYPE;
    
    SM_DB_TYPE one;
    one.name = malloc(sizeof(char) * (strlen("Alpha") + 1); //Allocate memory
    if (!one.name) {
       /* Error handling */
    } else {
        strcpy(one.name, "Alpha");
    }
    

提交回复
热议问题