I've been learning structs and I've come to the pointers to structs, where I'm currently struggling with this.
I've got this piece of code:
struct point {
int x;
int y;
} *ptr;
ptr->x = 8;
ptr->y = 8;
Running this gives a segmentation error. What I want to do is assign the value of 8 to x /y, to which, as far as I understand it, ptr is pointing to.
Your ptr is a pointer to struct point.
However, there is no struct point it is pointing to.
struct point {
int x;
int y;
} *ptr;
struct point pt; // add this...
ptr = &pt; // ...and this.
ptr->x = 8;
ptr->y = 8;
You have created a pointer called ptr but not initialized it. When you dereference it with ptr-> (or *ptr), you invoke undefined behavior which in your case is crashing the program (but could do anything).
This would be better:
struct point {
int x;
int y;
};
struct point sp = {0,0};
struct point *ptr = &sp;
sp.x = 8;
ptr->y = 8;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With