Allocate memory for a struct with a character pointer in C

后端 未结 6 425
礼貌的吻别
礼貌的吻别 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:40

    malloc the outer struct will only allocate 1 byte memory pointed by *word since it is a 'char *' type. If you want to allocate more than 1 byte of memory pointed by word, there are 2 options:

    1. Like what you said, declare it as char word[50] instead of `char *'
    2. malloc/calloc (I personally prefer calloc, saving you the trouble of zeromemory, which is a very important..) the outer struct, then malloc/calloc the inner word as well. Remember to call free twice as well in this case.

提交回复
热议问题