因此,我正在尝试构建一个链表,它可以接受任何数据类型,更像是一个非同源列表。
#define CNode malloc (sizeof(listnode));
#define CNodeContent malloc (sizeof(content));
typedef enum datatypes {
CHAR,
INT ,
FLOAT,
STRING,
LIST
}datatype;
typedef struct contentInfo {
void *data;
datatype type;
}content;
typedef struct node {
content* val;
struct node *next;
} listnode;
typedef listnode* list;
// Creating content
//----------------------------------------------------------------------------------------------
content* createContentInt(int val) {
content *newContent = CNodeContent;
newContent->type= INT;
newContent->data = &val;
return newContent;
}
content* createContentFloat(float val) {
content *newContent = CNodeContent;
newContent->type= FLOAT;
(newContent->data) = &val;
return newContent;
}
content* createContentChar(char val) {
content *newContent = CNodeContent;
newContent->type= CHAR;
newContent->data = &val;
return newContent;
}
content* createContentString(char* val) {
content *newContent = CNodeContent;
newContent->type= STRING;
newContent->data = val;
return newContent;
}
//---------------------------------------------------------------------------------------------
// List Functions
list createList(content *cont) {
list newnode = CNode;
printf("\n--%d--value: %d ",(cont->type),*((int*)cont->data));
newnode->val = cont;
printf("<leh %d >",(newnode->val->type));
newnode->next= NULL;
return newnode;
}
int main() {
list llist = createList(createContentInt(4));
content * c = createContentInt(5);
printf("Main-> %d <",(*(int*)c->data));
createList(c);
/* append(llist,c); */
/* display(llist); */
/* append(llist,createContentInt(5)); */
/* append(llist,createContentInt(6)); */
/* display(llist); */
return 0;
}所以问题来了:
当我调用createContentInt(4)时,它会正确地返回内容节点,但只要我对相同的内容节点调用createList或append函数,值data就会被设置为0。
我检查了createContentInt的返回值,除了在createList或append中之外,并不是所有的东西都能正常工作。
此外,content->type也有适当的价值,但data已经失去了它的。
我在论坛上的这种搜索中痛苦万分,但似乎找不到为什么将值设置为0的原因。我想出的另一件事是,如果我使用这样的东西:
newContent->data = (int*)4;代码运行得很好。有什么关系?
请有人给出一些关于它为什么不起作用的见解。任何替代解决方案都将受到高度赞赏,尽管我更倾向于了解它为什么不起作用。
发布于 2017-01-11 21:26:46
newContent->data = &val;将函数参数的地址(在堆栈上)赋给data。
如果通过连续调用重用保存val的寄存器,则会覆盖data的内容。
更一般地,一旦退出函数,val的地址就可以在空闲时重用,因此data将指向垃圾。
相反,您可以这样做,例如:
newContent->data = malloc(sizeof(TYPE)); // Set TYPE to INT/CHAR/...
// test return of malloc
memcpy(newContent->data, &val, sizeof(TYPE));
// Note that you will need an extra function to free() the allocated memoryhttps://stackoverflow.com/questions/41592051
复制相似问题