对通过指针访问结构成员感到困惑 [英] Confused about accessing struct members via a pointer

查看:54
本文介绍了对通过指针访问结构成员感到困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C 新手,对通过指针引用结构成员时得到的结果感到困惑.有关示例,请参见以下代码.当我第一次引用 tst->number 时发生了什么?我在这里缺少什么基本的东西?

I'm new to C, and am confused by results I'm getting when referencing a member of a struct via a pointer. See the following code for an example. What's happening when I reference tst->number the first time? What fundamental thing am I missing here?

#include <stdio.h>
#include <stdlib.h>

typedef struct {
   int number;
} Test;

Test* Test_New(Test t,int number) {
    t.number = number;
    return &t;
}    

int main(int argc, char** argv) {    
    Test test;
    Test *tst = Test_New(test,10);
    printf("Test.number = %d\n",tst->number);
    printf("Test.number = %d\n",tst->number);
    printf("Test.number = %d\n",tst->number);
}

输出为:

Test.number = 10
Test.number = 4206602
Test.number = 4206602

推荐答案

当您将测试传递到您的 Test_New 函数时,您是通过值传递它,因此在堆栈上为您的 Test_New 函数的函数作用域创建了一个本地副本.由于您返回了变量的地址,一旦函数返回堆栈就没有用了,但您已经返回了一个指向旧堆栈上的结构的指针!所以你可以看到你的第一次调用返回了正确的值,因为没有任何东西覆盖你的堆栈值,但随后的调用(都使用堆栈)覆盖了你的值并给你错误的结果.

When you pass test into your Test_New function, you are passing it by value and so a local copy is made on the stack for the function scope of your Test_New function. Since you return the address of the variable, once the function returns the stack is useless but you've returned a pointer to a struct on the old stack! So you can see that your first call returns the correct value since nothing has overwritten your stack value but the subsequent calls (which all use the stack) overwrite your value and give you erroneous results.

要正确地做到这一点,请重写您的 Test_New 函数以获取一个指针并将指向结构的指针传递给函数.

To do this correctly rewrite your Test_New function to take a pointer and pass the pointer to the struct into the function.

Test* Test_New(Test * t,int number) {
    t->number = number;
    return t;
}

int main(int argc, char ** argv)  {
   Test test;
   Test * tst = Test_New(&test,10);

   printf("Test.number = %d\n",tst->number);
   printf("Test.number = %d\n",tst->number);
   printf("Test.number = %d\n",tst->number);

}

这篇关于对通过指针访问结构成员感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆