这是我长期以来一直不清楚(就范围而言)的一个特定场景。
考虑代码
#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 编程的内容来看,它应该是超出这个范围的垃圾。然而它返回一个正确的结果。是不是因为st = x;线上的“=” 将 x 的值复制到 st?
编辑 - -
经过一些实验
#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
正如预期的那样。