我正在编写一个简单的 c++ 代码,以在代码块中使用 g++ 初始化结构的成员。以下代码编译时没有任何错误或警告,但是当我运行代码时,出现错误
try.exe has stopped working.
我认为当我为整数成员 val 赋值时会出现问题。
#include<iostream>
struct node{
int val;
node *next;
}*head;
int main(){
head->val=10;
std::cout<<head->val;
return 0;
}
最佳答案
head
是一个未初始化的指针。它指向的位置未定义,但您的代码可能无法写入,当您尝试在 head->val=10;
要解决这个问题,您需要为head
分配内存
head = new node();
head->val=10;
....
delete head;
或者,您实际上并不需要示例中的指针
struct node{
int val;
node *next;
}head;
int main(){
head.val=10;
std::cout<<head.val;
关于c++ - 在 C++ 中使用指针初始化结构成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19333141/