Take the 2-minute tour ×

I am experimenting with Struct, pointers and typedef in the code below. I want to create a pointer to a struct that I made up. Then I want to manipulate the struct's members using the -> operator.

The below code compiles fine, however, when I run the program it produces a segmentation fault.

Can someone please help explain where my logic went wrong?

Thank you.

struct Structure1 {
char c;
int i;
float f;
double d;

typedef Structure1* structp;

int main(){
structp s1, s2;
s1->c = 'a';
s1->i = 1;
s1->f = 3.14;
s1->d = 0.00093;
s2->c = 'a';
s2->i = 1;
s2->f = 3.14;
s2->d = 0.00093;
share|improve this question
Please accept an answer to this question (as well as your others) –  0x499602D2 Jul 13 '13 at 0:40
add comment

2 Answers

up vote 3 down vote accepted
structp s1, s2;

You've declared two pointers, s1 and s2 but they don't point anywhere yet! You need to allocate memory for these pointers using new.

s1 = new Structure1();
s1->c = 'a';
s1->i = 1;
// ...

Don't forget to delete the memory afterwards:

delete s1;

See this answer why the parentheses in new Structure1() make a difference. Also, note that there are other ways to obtain a pointer to an object, such as using the & operator, but in this particular case, I think you want to allocate memory.

share|improve this answer
Awesome!!!! thanks so much :D –  SeekingAlpha Jul 12 '13 at 1:14
Do note that the new operator is not the only way to get an address of a valid object. You can also apply the & operator to an existing object of the correct type. Or, in this case of "plain old data", cast any pointer to a memory region which is large enough. –  Ben Voigt Jul 12 '13 at 1:31
add comment

Pointers are objects in memory that point to another object. When using the indirection operator it causes the pointer to be dereferenced. For example, this:


is the same as:


When you dereference a pointer, it returns a reference to the object that it points to. If there is no object that it points to (or it points to nullptr), deferencing it gives your program Undefined Behavior.

The solution would be to create a new instance of a class on the heap and return a pointer to it. That is what new does:

Structure1 *structp = new Structure1();

It makes sense once you realize that pointers are not the actual objects, they are simply memory addresses. If you don't allocate space or assign to it a memory address, it will remain uninitialized and filled in with garbage. Just like a regular object, why would you want to use an initialized pointer?

share|improve this answer
add comment

Your Answer


