链表实现的栈中pop函数如何正确返回字符串值?
链表实现字符串栈的pop函数问题
编辑说明: 我对代码进行了修改,修改后的代码如下,感谢各位的建议!
typedef struct node{ struct node* next; char value[]; }node; typedef struct stack{ node* top; }stack; node* init_node(char c[]) { node* p = (node*)malloc(sizeof(node) + strlen(c) + 1); if (p == NULL) return NULL; strcpy(p->value, c); p->next = NULL; return p; } stack* init_stack() { stack* s = (stack*)malloc(sizeof(stack)); if (s == NULL) return NULL; s->top = NULL; return s; } int push(stack* *s, char c[]) { node* p = init_node(c); if (p == NULL) return -1; p->next = (*s)->top; (*s)->top = p; return 0; } bool isEmpty(stack* s) { return (s->top == NULL); } char* pop(stack* *s) { if (!isEmpty(*s)) { node* p = (*s)->top; char* res = (char*)malloc(sizeof(char)); strcpy(res, p->value); (*s)->top = p->next; free(p); return res; } }
如你所见,我将res指针放入pop()函数中,并在初始化时为其分配内存,这确实能运行!
我正在完成一个练习,要求用链表节点实现栈,且每个节点的值为字符串而非普通数字。但我找不到让pop()函数正确返回字符串值的方法,程序出现访问未分配内存的未定义行为,错误码为-1073741819。
以下是我用于栈操作的初始代码:
typedef struct node{ struct node* next; char value[]; }node; typedef struct stack{ node* top; }stack; char* res; node* init_node(char c[]) { node* p = (node*)malloc(sizeof(node) + strlen(c) + 1); if (p == NULL) return NULL; strcpy(p->value, c); p->next = NULL; return p; } stack* init_stack() { stack* s = (stack*)malloc(sizeof(stack)); if (s == NULL) return NULL; s->top = NULL; return s; } int push(stack* *s, char c[]) { node* p = init_node(c); if (p == NULL) return -1; p->next = (*s)->top; (*s)->top = p; return 0; } bool isEmpty(stack* s) { return (s->top == NULL); } const char* pop(stack* *s) { if (!isEmpty(*s)) { node* p = (*s)->top; strcpy(res, p->value); (*s)->top = p->next; free(p); return res; } }
除pop()外其他函数都能正常工作,之前我遇到过结构体柔性字符串成员的内存分配问题,但这次不是这个原因,请问该怎么修改代码?
内容的提问来源于stack exchange,提问作者Kurakami Genya
相关产品推荐
相关产品推荐

