Q:

Struct and Pointers C++

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

A:

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.

