robarteman
robarteman

Reputation: 11

Pointer to a struct doesn't work until I create an unused variable with a default value

I do not understand C programming pointers very well and I've tried searching the internet looking for information about using simple pointers related to structures. I have this simple program :

#include <stdio.h>

typedef struct
{
      int ia;
      int ib;
} num;

int main()
{

     num *pn;

     //int a = 4;

     pn->ia = 5;
     printf("Hello, I made it this far!\n");
     pn->ib = 10;
     pn->ia = pn->ib;

     printf("num = %d\n", pn->ia);

     return 0;
}

This code doesn't work until I uncomment the unused integer 'int a = 4;'

It doesn't seem to matter if I use gcc 32bit or 64 bit on Windows 10.

I want to learn to do this the right way and I don't believe that an unused variable should make it work!

Upvotes: 1

Views: 152

Answers (2)

S.S. Anne
S.S. Anne

Reputation: 15576

You do not allocate storage for pn to point to.

Make it an array like this and you should be able to use it in the same way:

num pn[1];

Upvotes: 0

0___________
0___________

Reputation: 67476

your pn is not initialized. Your program invokes Undefined Behavior and is simply wrong

You need to initialize it static or dynamic way.

num nl;
num *np = &nl;

or

num *np = malloc(sizeof(*np));

Upvotes: 6

Related Questions