gpt4 book ai didi

c++ - C变量范围特定问题

转载 作者:太空宇宙 更新时间:2023-11-04 14:38:47 24 4
gpt4 key购买 nike

这是一个我长期以来一直不清楚(在范围方面)的特定场景。

考虑代码

#include <stdio.h>


typedef struct _t_t{
int x;
int y;
} t_t;

typedef struct _s_t{
int a;
int b;
t_t t;
}s_t;

void test(s_t & s){
t_t x = {502, 100};
s.t = x;
}


int main(){
s_t s;
test(s);

printf("value is %d, %d\n", s.t.x, s.t.y);
return 0;
}

输出是

value is 502, 100

让我有点困惑的是以下内容。声明

t_t x

在函数测试的范围内声明。所以从我读到的关于 C 编程的内容来看,它应该是超出这个范围的垃圾。但它返回正确的结果。是不是因为线上的“=” s.t = x;将 x 的值复制到 s.t 中?

编辑---

经过一些实验

#include <stdio.h>


typedef struct _t_t{
int x;
int y;
} t_t;

typedef struct _s_t{
int a;
int b;
t_t t;
}s_t;

void test(s_t & s){
t_t x = {502, 100};
t_t * pt = &(s.t);
pt = &x;
}


int main(){
s_t s;
test(s);

printf("value is %d, %d\n", s.t.x, s.t.y);
return 0;
}

实际输出

value is 134513915, 7446516

正如预期的那样。

最佳答案

Is it because the "=" on the line s.t = x; copies the values of x into s.t?

是的。

顺便说一下,这是 C++。您已经将局部的“s”作为对函数的引用传递给 main,它修改了它。因为它是引用,而不是拷贝,所以它会影响调用者的“s”。

关于c++ - C变量范围特定问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1435766/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com