allocating memory for a struct when it includes a string

大憨熊 提交于 2019-12-24 02:25:13

问题


Suppose if i have a struct like this

struct node{ // note that i have changed the struct code according to my convenience

    char* lastname;
    char* employeeID;

    struct node* nextRecord;
} ;
typedef struct node myRecord;

Now I am allocating memory for the sirst node as below

headptr=malloc(sizeof(myRecord));

The struct inludes two strings. when I store something in headptr->lastname where does it get stored? shoul I allocate memory for those two strings explicitly?


回答1:


when I store something in myRecord->lastname where does it get stored?

It will lead to undefined behaviour.

should I allocate memory for those two strings explicitly?

Yes, you have to allocate for the struct members lastname and employeeIDas too.

Like this:

headptr=malloc(sizeof(myRecord));

headptr->lastname = malloc(n1); // Alllocate n1 bytes
headptr->employeeIDas = malloc(n2); // Alllocate n2 bytes

However, if you assign string literals to those pointers, then you don't need to allocate memory.

headptr->lastname = "last name";
headptr->employeeIDas = "12345";

Here, you are making the pointers to point to string literals which have static storage duration.


String literals can't be modified in C (attempting to modify invokes undefined behaviour). If you intend to modify them, then you should take former approach (allocate memory) and copy the string literals.

headptr->lastname = malloc(n1); // Alllocate n1 bytes
headptr->employeeIDas = malloc(n2); // Alllocate n2 bytes

and then copy them:

strncpy(headptr->lastname, "last name", n1);
headptr->lastname[ n1 - 1 ] = 0;
strncpy(headptr->employeeIDas, "12345", n2);
headptr->employeeIDas[ n2 - 1 ] = 0;



回答2:


Yes, you need to explicitly allocate memory for those. Your structure doesn't include strings, it includes only pointers for which the memory will be allocated as part of memory allocation for the structure. It's your own decision to use these pointers as heads for strings and you need to provide an explicitly allocated space for them, which has nothing to do with the original struct.




回答3:


No, you do not have to allocate memory for the strings. If you assign a string directly, it will stored in a readonly section (modifying will not work). If you want it modifiable, you will have to allocate memory.

headptr->lastname = "whatever"; // will work but no modify operations possible

or

headptr->lastname = malloc(NUM_BYTES);
headptr->lastname = "abc"; // modifiable string


来源:https://stackoverflow.com/questions/19263717/allocating-memory-for-a-struct-when-it-includes-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!