when I store something in myRecord->lastname where does it get stored?
这将导致undefined behaviour。
should I allocate memory for those two strings explicitly?
是的,你要分配的结构成员lastname
和employeeIDas
了。
像这样:
headptr=malloc(sizeof(myRecord));
headptr->lastname = malloc(n1); // Alllocate n1 bytes
headptr->employeeIDas = malloc(n2); // Alllocate n2 bytes
但是,如果分配字符串文本到这些指针,那么你并不需要分配内存。
headptr->lastname = "last name";
headptr->employeeIDas = "12345";
在这里,你正在使指针指向具有静态存储持续时间的字符串文字。
字符串文字不能在C中修改(试图修改调用未定义的行为)。如果你打算修改它们,那么你应该采取以前的方法(分配内存)并复制字符串文字。
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;
我不相信 '无处' 在这里正确的单词(UB依然屹立,肯定)。而且,如果NUM_BYTES是不变的,它应该在数组结构内(与问题没有直接关系,而是改进)。 – keltar
刚刚用变量'n1'和'n2'代替它,如果这样做更好。 –
“*但是,如果将字符串文字分配给这些指针,则不需要分配内存*” - 并且一旦尝试修改就会得到UB。 – SomeWittyUsername