我正在遍历一个包含两个字段的节点列表:next和size。代码中有一点需要我在新节点中链接,我遇到了麻烦。我发现代码段出错的地方就像这样。请注意,curr是列表中的当前节点,我需要在curr和curr-> next之间链接temp。
Node* temp = NULL;
temp = ((curr + 1) + a_memory_offset_int); //calculate the address where temp should go
temp->next = curr->next; //Seg faults here
temp->size = some_other_int; //Seg faults here as well
curr->next = temp;
我是否有某种方法尝试为NULL节点设置字段?语法是否有问题(因为我确信逻辑是正确的)?
答案 0 :(得分:1)
链表节点的内存地址并不重要 - 你不应该自己计算它,而是调用malloc,然后将其链接起来。
更像这样:
Node* temp = NULL;
temp = malloc(sizeof(Node)); // create a new node, allocating fresh memor
temp->next = curr->next; // should be fine now...
temp->size = some_other_int;
curr->next = temp;
答案 1 :(得分:1)
验证指针算术的示例程序。
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int size;
struct node * next;
} Node;
int main() {
void *memory = malloc(10*sizeof(Node));//allocate of Node * 10
Node *curr = memory;
Node *temp = NULL;
temp = curr + 1;
temp->size = 999;
printf("%lu\n", sizeof(Node));
//16
printf("%p,%p\n", (void*)curr, (void*)temp);
//00000000004D67B0,00000000004D67C0 <- difference is 16
int a_memory_offset_int = 16;
temp = curr + a_memory_offset_int;
if(temp > &curr[9])//curr[9] is last element
printf("It is outside the allocated memory\n");//this display
temp = curr + a_memory_offset_int/sizeof(Node);
printf("%d\n", temp->size);//999
return 0;
}
答案 2 :(得分:1)
如果没有看到更多代码,我怀疑您可能无法理解a_memory_offset_int
正在做什么。它正在做与+ 1
完全相同的事情,也就是说它正在做指针算术。这样:
temp = ((curr + 1) + a_memory_offset_int);
相当于:
temp = (Node*)(((char *)curr + 1*sizeof(Node)) + a_memory_offset_int*sizeof(Node));
你真正想要的是:
temp = (Node*)(((char *)curr + 1*sizeof(Node)) + a_memory_offset_int);
请注意,唯一的区别是a_memory_offset_int
乘以sizeof(Node)
。更简化,这就是你想要的:
temp = (Node*)((char *)curr + a_memory_offset_int) + 1;