Allocate memory for a struct with a character pointer in C

后端 未结 6 438
礼貌的吻别
礼貌的吻别 2021-02-02 02:22

I was struggling to fix a code today, then I come across something similar to:

typedef struct {
int a; 
int b; 
int c;
int d;
char* word;
} mystruct;

int main(i         


        
6条回答
  •  礼貌的吻别
    2021-02-02 02:54

    You are allocating only memory for the structure itself. This includes the pointer to char, which is only 4 bytes on 32bit system, because it is part of the structure. It does NOT include memory for an unknown length of string, so if you want to have a string, you must manually allocate memory for that as well. If you are just copying a string, you can use strdup() which allocates and copies the string. You must still free the memory yourself though.

     mystruct* structptr = malloc(sizeof(mystruct));
     structptr->word = malloc(mystringlength+1);
    
     ....
    
     free(structptr->word);
     free(structptr);
    

    If you don't want to allocate memory for the string yourself, your only choice is to declare a fixed length array in your struct. Then it will be part of the structure, and sizeof(mystruct) will include it. If this is applicable or not, depends on your design though.

提交回复
热议问题