0

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

Edited by Narue: Added code tags

4
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by Moschops
0

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;
}
0

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.