我该怎么做来修复这个程序?

时间:2014-02-10 21:57:41

标签: c

我对以下程序有疑问: 它打印:

  

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);
}

2 个答案:

答案 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);
}