[英]Why is this simple hello world code segfaulting?
Excuse the beginner level of this question. 请问这个问题的初学者水平。 I have the following simple code, but it does not seem to run. 我有以下简单的代码,但它似乎无法运行。 It gets a segmentation fault. 出现分段错误。 If I replace the pointer with a simple call to the actual variable, it runs fine... I'm not sure why. 如果我将指针替换为对实际变量的简单调用,它将运行良好...我不确定为什么。
struct node
{
int x;
struct node *left;
struct node *right;
};
int main()
{
struct node *root;
root->x = 42;
printf("Hello world. %d", root->x);
getchar();
return 0;
}
What is wrong with this code? 此代码有什么问题?
struct node *root;
root->x = 42;
You're dereferencing an uninitialized pointer. 您正在取消引用未初始化的指针。 To allocate storage for the node: 为节点分配存储:
struct node *root = malloc(sizeof(struct node));
You could also allocate a node on the stack: 您还可以在堆栈上分配一个节点:
struct node root;
root.x = 42;
In order to use a pointer to access something, the pointer must be pointing at that something. 为了使用指针访问某物,该指针必须指向该东西。 In order for the pointer to be pointing at that something, that something must exist. 为了使指针指向某物,该物必须存在。 Creating a pointer does not create anything for it to point at. 创建指针不会为其指向创建任何内容。 You must do so explicitly, either by dynamic allocation ( malloc()
), stack allocation (ie a local variable) or by pointing to something that already exists (eg a static
instance, such as a global; a value that was passed in as a parameter; etc.). 您必须通过动态分配( malloc()
),堆栈分配(即局部变量)或指向已存在的对象(例如static
实例,例如全局变量;以参数;等等。
After struct node *root;
在struct node *root;
line add the 行添加
root = (sturct node*) malloc(sizeof(struct node));
Also, before Return 0
line add the 另外,在Return 0
行之前添加
free(root);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.