简体   繁体   English

在我创建一个具有默认值的未使用变量之前,指向结构的指针不起作用

[英]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.我不太了解 C 编程指针,我尝试在互联网上搜索有关使用与结构相关的简单指针的信息。 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;'在我取消注释未使用的整数 'int a = 4;' 之前,此代码不起作用

It doesn't seem to matter if I use gcc 32bit or 64 bit on Windows 10.我在 Windows 10 上使用 gcc 32 位还是 64 位似乎无关紧要。

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.您的pn未初始化。 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.您没有为pn指向的分配存储空间。

Make it an array like this and you should be able to use it in the same way:使它成为这样的数组,您应该能够以相同的方式使用它:

num pn[1];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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