这是一个特定的场景,我很长时间以来一直不清楚(在范围上)。C变量作用域特定问题
考虑代码
#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
预期。
有关该语言的争论点很重要。你的titla和标签说“c”,但你的代码是“C++”。 – dmckee
不是C.这是C++,带有强调C的重音。 – pmg
被重新标记以反映投诉 – Novelocrat