我有以下 C 代码:
typedef struct DListNode_ {
void *data;
struct DListNode_ *prev;
struct DListNode_ *next;
} DListNode;
typedef struct DList_ {
int size;
DListNode *tail;
DListNode *head;
} DList;
void insert(DList * list, DListNode * element, int data) {
DListNode * new_element = (DListNode *)malloc(sizeof(DListNode));
new_element->data = &data;
if (list->head==NULL) {
list->head=list->tail=new_element;
list->size++;
return;
}
if(element == NULL) {
// handle size==0?
new_element->next=list->head;
list->head->prev=new_element;
list->head=new_element;
list->size++;
} else {
printf("Not yet implemented!\n");
}
}
void printNodes(DList *list) {
DListNode * pointer = list->head;
if (pointer!=NULL) {
int v= *((int*)pointer->data);
printf("Node has value: %d\n", v);
while (pointer->next != NULL) {
v = *((int*)pointer->data);
printf("Node has value: %d\n", v);
pointer=pointer->next;
}
}
}
int main(int argc, const char * argv[])
{
int e0 = 23;
int e1 = 7;
int e2 = 11;
DList *list = (DList *)malloc(sizeof(DList));
initList(list);
assert(count(list)==0);
insert(list, NULL, e0);
assert(count(list)==1);
insert(list,NULL, e1);
assert(count(list)==2);
insert(list,NULL, e2);
assert(count(list)==3);
printNodes(list);
return 0;
}
我有一些问题:
- 是否还为 data、prev、next 指针分配空间,或者我是否需要手动在每个指针上调用 malloc那些指针?
- 当我打印每个节点中数据指针的内容时,即使我插入 23、7 和 11 并将数据指针设置为 int 的地址,它们的值仍然是 3:* * new_element->data = &data;**。
(C入门教材已订)
编辑:
插入现在采用指向数据的空指针:
// Insert data as the new head
void insert(DList *list, DListNode *element, void *data) {
DListNode *new_element = malloc(sizeof(DListNode));
new_element->data = data;
if (list->head==NULL) {
list->head=list->tail=new_element;
list->size++;
return;
}
if(element == NULL) {
new_element->next=list->head;
list->head->prev=new_element;
list->head=new_element;
list->size++;
} else {
printf("Not yet implemented!\n");
}
}
我主要做的是:
int main(int argc, const char * argv[])
{
int i0=7;
int *ip0 = malloc(sizeof(int));
ip0 = &i0;
int i1=8;
int *ip1 = malloc(sizeof(int));
ip1 = &i1;
int *ip2 = malloc(sizeof(int));
int i2=44;
ip2 = &i2;
DList *list = malloc(sizeof(DList));
initList(list);
// create some nodes
assert(count(list)==0);
insert(list, NULL, ip0);
assert(count(list)==1);
insert(list,NULL, ip1);
assert(count(list)==2);
insert(list,NULL, ip2);
assert(count(list)==3);
printNodes(list);
return 0;
}
输出:
Node has value: 44
Node has value: 44
Node has value: 8
但应该是:
Node has value: 44
Node has value: 8
Node has value: 7
最佳答案
malloc(sizeof(DListNode))
为一个DListNode
分配空间,根据定义,它由一个void*
和两个 DListNode 指针。但它不会初始化这些指针。您正在将
data
参数的地址分配给insert
。这是一个指向临时对象的指针,一旦insert
返回就会失效。程序的行为是未定义的。简单的解决方案是将void *data
替换为int data
。
关于c - 结构体中的 malloc 和指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16550118/