when I store something in myRecord->lastname where does it get stored?
它将导致未定义的行为。
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;