当结构包含字符串时为结构分配内存 [英] allocating memory for a struct when it includes a string
问题描述
假设我有这样的结构
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;
现在我为如下所示的sirst节点分配内存
Now I am allocating memory for the sirst node as below
headptr=malloc(sizeof(myRecord));
该结构包含两个字符串.当我将某些东西存储在headptr-> lastname中时,该文件存储在哪里?我应该为这两个字符串显式分配内存吗?
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?
推荐答案
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?
是的,您还必须为结构成员lastname
和employeeIDas
分配.
Yes, you have to allocate for the struct members lastname
and employeeIDas
too.
赞:
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.
不能在C中修改字符串文字(尝试修改会调用未定义的行为).如果要修改它们,则应该采用以前的方法(分配内存)并复制字符串文字.
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
然后复制它们:
strncpy(headptr->lastname, "last name", n1);
headptr->lastname[ n1 - 1 ] = 0;
strncpy(headptr->employeeIDas, "12345", n2);
headptr->employeeIDas[ n2 - 1 ] = 0;
这篇关于当结构包含字符串时为结构分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!