Hi folks,

I am learning C++ programming.
Below mentioned program giving segmentation fault ONLY WHEN if I declare 'struct s a;'
ABOVE 'struct s *b;'.
Can anybody tell me the reason?

#include<iostream>
using namespace std;

struct s
{
 int m;
};

int main()
{
 struct s a; // if I put this below 'struct s *b; then i wont get segmentation fault
 struct s *b;
 b->m = 5;
 cout<<"m="<<b->m<<endl;

return 0;
}

output:
./a.out
Segmentation fault

you forgot to make pointer b point to anything. struct s* b = &a;

Thanks Ancient Dragon, But if i remove or move struct s a; then code will work :-O:-/

eg:

#include<iostream>
using namespace std;
 
struct s
{
 int m;
};
 
int main()
{
 //struct s a;[B] moving this below to struct s *b; NO segfault [/B]
 struct s *b;
 struct s a;


 b->m = 5;
 cout<<"m="<<b->m<<endl;
 
return 0;
}

It's pure luck. What you are doing is illegal. It can work or it cannot.

As an aside, this is C++; you don't need to keep repeating "struct" every time you create a new instance of one.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.