ldo*_*dog 0 c++ scope parameter-passing pass-by-reference argument-passing
这是一个特定的场景,我很长一段时间都不清楚(在范围方面).
考虑代码
#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;
}
Run Code Online (Sandbox Code Playgroud)
输出是
value is 502, 100
Run Code Online (Sandbox Code Playgroud)
对我来说有点混乱的是以下几点.声明
t_t x
Run Code Online (Sandbox Code Playgroud)
在函数测试的范围内声明.所以从我读到的关于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;
}
Run Code Online (Sandbox Code Playgroud)
实际输出
value is 134513915, 7446516
Run Code Online (Sandbox Code Playgroud)
正如所料.
是因为行上的"="st = x; 将x的值复制到st?
是.
顺便说一句,这是C++.你已经将"s"本地传递给main作为函数的引用,它修改了它.因为它是一个引用,而不是一个副本,它会影响调用者的"s".
小智 6
Run Code Online (Sandbox Code Playgroud)t_t x = {502, 100}; s.t = x;
在第一次测试中,您指示编译器复制x into 的值s.t- 这可以按预期工作.局部变量x超出范围,但从不在函数外部引用 - 它最初包含的数据被复制到局部变量的t成员中.如果您反而写道,那将是有效的:main()s
t_t x = {502, 100};
s.t.x = x.x;
s.t.y = x.y;
Run Code Online (Sandbox Code Playgroud)
在第二个测试中,您指定一个指向另一个指针的指针,这两个指针都被声明为局部变量.这没有任何用处 - 它的价值s.t仍然没有初始化.我已经注释了代码以帮助您遵循它:
t_t x = {502, 100}; // local variable x initialized with 502, 100
t_t * pt = &(s.t); // local variable pt initialized with ADDRESS OF s.t
pt = &x; // local variable pt re-assigned to hold address of local variable x
// local variables go out of scope, output parameter s remains unmodified
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
398 次 |
| 最近记录: |