[英]A weird error when passing a struct pointer to a function in C
I've written a simple C test program to practice using structs. 我编写了一个简单的C测试程序来练习使用结构。 However I can't understand what's wrong with the code;
但是我不明白代码有什么问题。 it seems that the first printout of either the integer or the double field clears both fields.
似乎整数或双精度字段的第一次打印输出会清除两个字段。 What's my mistake here?
我这是怎么了
the code: 编码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Dummy {
int i;
double d;
char s[8];
};
void print(struct Dummy *dummy) {
printf("%lf ", dummy->d);
printf("%lf ", dummy->d);
printf("%d ", dummy->i);
printf("%s\n", dummy->s);
}
void set(struct Dummy **dummy) {
struct Dummy duh;
duh.i = 1;
duh.d = 3.14;
strcpy(duh.s, "Hello!");
*dummy = &duh;
}
int main(int argc, char **argv) {
struct Dummy *dummy;
set(&dummy);
print(dummy);
return 0;
}
its output: 其输出:
3.140000 0.000000 0 Hello!
Thanks a lot! 非常感谢!
You've invoked undefined behavior by assigning the address of a local variable in set
and returning it. 通过在
set
分配局部变量的地址并返回它,可以调用未定义的行为。
*dummy = &duh;
duh
is no longer valid after set
returns. set
返回后duh
不再有效。
In set you assign **dummy to variable duh which is defined in the scope of the function. 在set中,将** dummy分配给在函数范围内定义的变量duh。 This means that duh will be lost at the end of the function, even if you keep a pointer to it.
这意味着duh将在函数末尾丢失,即使您保留指向它的指针。 To correct assign directly to the function's parameter
正确直接分配给函数的参数
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Dummy {
int i;
double d;
char s[8];
};
void print(struct Dummy *dummy) {
printf("%lf ", dummy->d);
printf("%lf ", dummy->d);
printf("%d ", dummy->i);
printf("%s\n", dummy->s);
}
void set(struct Dummy *dummy) {
dummy->i = 1;
dummy->d = 3.14;
strcpy(dummy->s, "Hello!");
}
int main(int argc, char **argv) {
struct Dummy dummy;
set(&dummy);
print(dummy);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.