简体   繁体   中英

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!

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));

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM