Shri
Shri

Reputation: 834

initialize structure members using pointer in c++

i am writing a simple c++ code to initialize members of a structure using g++ in codeblocks. the following code compiles without any errors or warnings, but when i run the code, i am getting an error

try.exe has stopped working.

i think the problem occurs when i am assigning value to the integer member val.

#include<iostream>

struct node{
  int val;
  node *next;
}*head;

int main(){
  head->val=10;
  std::cout<<head->val;
  return 0;
}

Upvotes: 0

Views: 152

Answers (1)

simonc
simonc

Reputation: 42185

head is an uninitialised pointer. The location it points to is undefined but likely isn't writeable by your code, causing a crash when you try to write to it in the line head->val=10;

To fix this, you need to allocate memory for head

head = new node();
head->val=10;
....
delete head;

Alternatively, you don't actually need the pointer in your example

struct node{
  int val;
  node *next;
}head;

int main(){
  head.val=10;
  std::cout<<head.val;

Upvotes: 4

Related Questions