gpt4 book ai didi

c - 复制指针时出现段错误

转载 作者:太空宇宙 更新时间:2023-11-04 06:41:28 27 4
gpt4 key购买 nike

下面的代码为什么会导致段错误?基本上在我将头指针复制到 temp 之后,头指针就消失了。

typedef struct address * paddress; // defines struct pointer

void addAddressToList(paddress head, int addr[])
{
if (head == NULL) {
//head->addrArray = addr; // if list is initially empty
} else {
paddress temp;
temp = head;
while (temp->right != NULL) {
temp = temp->right; // go to end of the list
}
paddress newAddress = (paddress)malloc(sizeof(paddress*));
newAddress->intAddr = addr;
newAddress->right = NULL;
newAddress->left = temp; // connect the new address
temp->right = newAddress;
}
}

main() {
paddress addressListHead;
addressListHead = (paddress)malloc(sizeof(paddress*));
int intAddr1[] = {1,2,3,4,5,6,7};
char hexAddr1[] = "123456";
int intAddr2[] = {16,14,13,12,11};
char hexAddr2[] = "fedcb";

addressListHead->intAddr = intAddr1;
addressListHead->hexAddr = hexAddr1;
addAddressToList(addressListHead, intAddr2);
}

最佳答案

paddress addressListHead;
addressListHead = (paddress)malloc(sizeof(paddress*));

似乎摆脱了编译错误,你已经将 malloc 返回到 paddress 的类型进行了类型转换。 addressListHead 是一个指针,这意味着它可以保存对象的地址,但不是指针的地址。 malloc here 语句不会创建对象。你需要改变这个-

addressListHead = (paddress)malloc(sizeof(paddress*));

addressListHead = (paddress)malloc(sizeof(struct address));

mainaddAddressToList 函数中。

段错误:

else {
paddress temp;
temp = head;
while (temp->right != NULL) {
temp = temp->right; // go to end of the list
}

我知道 paddress::right 是一个指针,您将它与 NULL 进行比较。但是什么是 temp::right 被初始化为。它指向一些垃圾地址,因此您不能要求它与NULL 进行比较。使其指向有效的内存位置。

关于c - 复制指针时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7641091/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com