C语言 在为嵌套结构分配值时出现分段错误


struct Address
{
char *streetName;
char *city;
};
struct Employee{
char name[32];
int empId;
struct Address *add[2];
struct Employee *next;
};
void fillAddress()
{
int i;
struct Employee* node = head;
while(node != NULL)
{
i = 0;
while(node->add[i++] != NULL);
strcpy(node->add[i-1]->streetName,strt[i]);< This is where the SEGFAULT OCCURS>
strcpy(node->add[i-1]->city,cty[i]);
node=node->next;
}
}

将值分配给节点>add[i-1]->streetName时,它崩溃了。尝试将内存分配给内部结构,但仍然崩溃。

这里的任何帮助都可以不胜感激。

谢谢 桑托什

这是因为结构 Address *add[2] 是指向地址类型结构的指针数组。这些指针无效,因为您没有分配它们。 应该是这样的

node->add[0] = malloc(sizeof(struct Address))
node->add[1] = malloc(sizeof(struct Address))

这也将失败,因为您尝试复制字符串,但字符串也没有分配。

node->add[0]->streetName = (char*)malloc(stringSize)
node->add[0]->city= (char*)malloc(stringSize)

在此之后,分配应该有效。

编辑:

struct Address
{
char* streetName;
char* city;
};
struct Employee {
char name[32];
int empId;
struct Address* add[2];
struct Employee* next;
};

struct Employee* createEmployee(int id, const char *name, const char *street1, const char *city1, const char *street2, const char*city2)
{
struct Employee* emp = (struct Employee*)malloc(sizeof(struct Employee));
emp->empId = id; 
strcpy(emp->name, name); 
emp->add[0] = (struct Address*)malloc(sizeof(struct Address));
emp->add[0]->streetName = (char*)malloc(256);
emp->add[0]->city = (char*)malloc(256);
strcpy(emp->add[0]->city, city1);
strcpy(emp->add[0]->streetName, street1);
emp->add[1] = (struct Address*)malloc(sizeof(struct Address));
emp->add[1]->streetName = (char*)malloc(256);
emp->add[1]->city = (char*)malloc(256);
strcpy(emp->add[1]->city, city1);
strcpy(emp->add[1]->streetName, street1);
return emp;
}
void insertEmployee(struct Employee** head, struct Employee* emp)
{
if (*head == NULL)
{
emp->next = NULL;
*head = emp;
}
else
{
emp->next = (*head);
*head = emp;
}
}
void printList(struct Employee* head)
{
while (head != NULL)
{
printf("%sn", head->name);
printf("%dn", head->empId);
printf("%sn", head->add[0]->city);
printf("%sn", head->add[0]->streetName);
printf("%sn", head->add[1]->city);
printf("%sn", head->add[1]->streetName);
head = head->next;
}
}

int main()
{
struct Employee* head = NULL;
struct Employee* emp = NULL;
emp = createEmployee(1, "name1", "street1", "city1", "street2", "city2");
insertEmployee(&head, emp);
emp = createEmployee(2, "name2", "street3", "city3", "street4", "city4");
insertEmployee(&head, emp);
printList(head);
return 0;
}

最新更新