我对以下程序有疑问: 它打印:
dst-> val in f1 = 6
dst.val in main = -528993792
我想修复此程序,以便打印
<= dst.val in main = 6
我该怎么做?
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
typedef struct my_struct myStruct;
struct my_struct
{
int val;
};
myStruct *f2(void)
{
myStruct *dst = malloc(sizeof(myStruct));
dst->val = 6;
return dst;
}
void f1(myStruct *dst)
{
dst = f2();
printf("**dst->val in f1=%d\n", dst->val);
}
int main()
{
myStruct dst;
f1(&dst);
printf("**dst.val in main=%d\n", dst.val);
}
答案 0 :(得分:0)
按值返回结构;不要使用指针和动态分配:
myStruct f2(void)
{
myStruct dst;
dst.val = 6;
return dst;
}
然后f1
将更常规地使用pass-by-pointer概念:
void f1(myStruct *dst)
{
*dst = f2();
printf("**dst->val in f1=%d\n", dst->val);
}
(实际上,我不确定它是否被称为“传递指针”或“传递参考”;可能后者是正确的)
答案 1 :(得分:0)
void f1(myStruct *dst){
myStruct *p = f2();
printf("**dst->val in f1=%d\n", p->val);
//dst is the address that was copied on the stack.
dst->val = p->val;//There is no meaning If you do not change the contents.
free(p);
}