list.c
char *get_value ( node *handle, char *name) {
node *current = handle;
while (current) {
if((!strcmp(current->name, name))) {
printf("=> %s %s %sn", __func__, current->name, current->value);
return current->value;
}
current=current->next;
}
return "";
}
void list_add(node **handle, char *name, char *value)
{
node *current, *new;
new = (node *)malloc(sizeof(node));
if (value == NULL) {
value = "";
}
strcpy(new->name, name);
strcpy(new->value, value);
new->next = NULL;
current = *handle;
if(*handle == NULL) {
*handle = new;
}
else {
while(current->next != NULL) {
current=current->next;
}
current->next = new;
}
}
从main.c调用此函数时,我无法检索 返回字符串(当前>值(并获取分段 故障,但能够以相同的功能打印。
主.c
struct node {
char name[100];
char value[512];
struct node *next;
};
node handle = NULL;
int main () {
....
list_add(&handle,"a","1");
printf("%sn", get_value (handle, name));
....
}
出现分段错误。
-
list_add 函数需要(指向(类型节点(意外的(数组(
void list_add(node **handle, ...
但您正在从 main: 传递类型为 node 的堆指针list_add(&handle,"a","1");
-
handle
的初始化不完整:node handle = NULL;
应该是(类似(node handle = {"","",NULL};
-
不要将堆栈内存(字符数组(返回给调用方(主(:
return "";
没关系,因为"只是一个字符("\0"(,但最好为"空"返回字符数组定义堆占位符。
工作代码:
struct node_ {
char name[100];
char value[512];
struct node_ *next;
} typedef node;
//declarations - linked list of type node, not array node** structure
char *get_value(node *handle, char *name);
void list_add(node *handle, char *name, char *value);
//initialise heap variable
node handle = {"","", NULL };
char _notFound__[1] = "";
int main() {
//passing address of heap variable 'handle'
list_add(&handle, "a", "1");
//passing address of heap variable 'handle'
printf("%sn", get_value(&handle, "a"));
return 0;
}
char *get_value(node *handle, char *name) {
//asign placeholder
node *current = handle;
//search linked list
while (current) {
if (!strcmp(current->name, name)) {
printf("=> %s %s %sn", __func__, current->name, current->value);
//return pointer to heap memory
return current->value;
}
current = current->next;
}
//return pointer to heap char-array memory
return _notFound__;
}
void list_add(node *handle, char *name, char *value)
{
node *current, *new;
//heap memory - requires destruction at heap scope
new = (node *)malloc(sizeof(node));
//initialise (copy construction)
(name) ? strcpy(new->name, name) : strcpy(new->name, "");
(value) ? strcpy(new->value, value) : strcpy(new->value, "");
new->next = NULL;
//insert new item
if (handle == NULL) {
handle = new;
}
else
{
//assign placeholder
current = handle;
//scroll to end
while (current->next != NULL)
{
current = current->next;
}
current->next = new;
}
}