Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers to structs and printing

Tags:

c

pointers

struct

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.

like image 286
George Waat Avatar asked Aug 18 '26 19:08

George Waat


2 Answers

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;
like image 198
DevSolar Avatar answered Aug 20 '26 09:08

DevSolar


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;
like image 43
John Zwinck Avatar answered Aug 20 '26 09:08

John Zwinck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!