我试图在C中实现一个链表,我有以下问题。我的节点定义如下:
struct node_t {
void* element;
node_t* previous;
node_t* next;
};
struct linkedlist_t {
node_t* head;
node_t* tail;
int length;
};
从链表中获取元素的方法具有以下签名:
// Gets an element from a linked list.
int linkedlist_get(linkedlist_t* linkedlist, unsigned int index, void* element);
因为我需要返回一个int来表示任何错误,所以我使用了一个out参数。但是,我不知道如何在方法中设置指针。我试着做:
element = current->element; // The callee doesn't see it.
*((char*)element) = *((char*)current->element); // Copies only the first char
另外,我不想将元素从一个内存区域复制到另一个内存区域,我希望linkedlist和被叫方都引用同一个内存区域。
最佳答案
您的get签名应更改为
int linkedlist_get(linkedlist_t* linkedlist, unsigned int index, void** element);
注意额外的*。在你的日常生活中
*element = current->element;
这是你想要的。显然,这是没有任何类型保护的老式C。小心你的记忆处理。
关于c - 如何在C中模拟出参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28785903/