Reputation: 7807
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;
}
Upvotes: 1
Views: 142
Reputation: 95335
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.
Upvotes: 4
Reputation: 96810
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:
s1->c;
is the same as:
(*s1).c;
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?
Upvotes: 2