【发布时间】:2021-12-28 18:24:24
【问题描述】:
这是将两个字符串打印在一起的代码,但每当我尝试运行它时,都会出现分段错误,但它编译时没有任何错误,有人可以帮忙吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
char *data; //string data in this node
struct node *next; //next node or NULL if none
} Node;
void print(Node *head); //function prototype print
Node *push_node(Node x, Node *strlist);
int main ()
{
Node node1;
Node node2;
Node *list = NULL;
strcpy(node1.data, "world");
push_node(node1, list);
strcpy(node2.data, "hello");
push_node(node2, list);
print(list);
return 0;
}
void print(Node *head)
{
Node *p = head;
while (p != NULL)
{
printf("%s", p->data);
p = p->next;
}
}
Node *push_node(Node x, Node *strlist)
{
x.next= strlist;
return &x;
}
【问题讨论】:
-
你没有为
node1.data分配任何空间——它只是复制到一个未初始化的指针。 -
您是否尝试过在调试器中逐行运行代码,同时监控所有变量的值,以确定您的程序在哪个点停止按预期运行?如果您没有尝试过,那么您可能想阅读以下内容:What is a debugger and how can it help me diagnose problems? 您可能还想阅读以下内容:How to debug small programs?。
-
请查看编译器警告。还有returning the address of a local variable 和
return &x;的罪行 -
基本上你对如何在 C 语言中使用指针有很多困惑。你需要查看你的教学材料,所以不是辅导服务。
标签: c linked-list undefined-behavior singly-linked-list strcpy