これは、私が長い間(範囲に関して)明確にしてこなかった特定のシナリオです。
コードを検討する
#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
予想通り。