c++ - 在 C++ 中使用指针初始化结构成员

标签 c++ struct g++

我正在编写一个简单的 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/

相关文章:

c++ - stdafx.h 的目的

c++ - 如何为布局激活 adjustsize()

swift - 对于 Swift 语言,初始化结构体和初始化类有什么区别? (我对编程还很陌生)

c - 源代码定义宽字符字符串和跨平台

c++ - 将 CRTP 用于析构函数是否安全?

C++ 设置指针等于 shared_ptr

c++ - static const Color 不完全适用于 Allegro5

c++ - gcc 是否支持宏定义中的多行原始字符串文字?

c - 将指向数组的指针传递给另一个函数 C

c - 使用堆上结构的结构初始化语法