Joseph Thweatt
Joseph Thweatt

Reputation: 326

Trying to access int from a struct pointer: compiles but does not run

I am trying to access an int from the struct pointer pPoint. The following code compiles, but when the program is run at the command prompt, my computer says the program has stopped working.

#include <stdio.h>
typedef struct point *pPoint;

struct point {
    int num;
    pPoint pt2; 
} pt1;

int main() {
    pt1.num = 9;
    pt1.pt2->num = 7;
    printf("%d ", pt1.num);
    printf("%d\n", pt1.pt2->num);
    return 0;
}

Where is the error and what needs to be changed?

Upvotes: 2

Views: 43

Answers (2)

Habib Kazemi
Habib Kazemi

Reputation: 2190

you should allocate memory for it like this:

int main() {
pt1.num = 9;
pPoint new = (struct point *)malloc(sizeof(struct point));
pt1.pt2 = new;
pt1.pt2->num = 7;
printf("%d ", pt1.num);
printf("%d\n", pt1.pt2->num);
return 0;
}

Upvotes: 0

mathematician1975
mathematician1975

Reputation: 21351

You have not allocated any memory for what the pt2 pointer points to. Therefore when you perform

pt1.pt2->num = 7;

you are writing a value to what is on the end of an uninitialised pointer. This is undefined behaviour. You need to make sure that pt2 points to a valid point struct before you try assigning values to the variables within it,

Upvotes: 3

Related Questions