声明为具有返回指针的函数的指针会导致两个指针的链?

时间:2016-10-30 00:43:01

标签: c pointers struct

如果我声明一个带有返回指针的函数的指针,我声明的指针是否与函数返回的指针相同,还是指向函数返回的指针?

示例:

typedef struct foo{
  int n;
} foo;

// this function returns a pointer to a structure foo
foo* returnPointer(){
  foo* tmp = malloc(sizeof(foo));
  tmp->n = 1;
  return tmp;
}

// if I do this, will abc be a pointer to a foo structure (the desired effect)
// or will it be a pointer to another pointer to a foo structure?
foo* abc = returnPointer();

2 个答案:

答案 0 :(得分:1)

abc将是您声明的内容。指向foo结构的指针。该函数还返回一个foo *(指向foo结构的指针)。所以有类型协议。

编辑:同样如@phaazon所述,该函数有错误(需要malloc)。

答案 1 :(得分:0)

宣布:

foo stFoo;    // create the struct
foo *tmp;     // create the pointer
tmp = &stFoo; // pointer receives the struct address

您只是创建一个指向结构的指针,而不是结构本身。您应该开始创建结构,然后设置指向它的指针,如下所示:

{{1}}

但请注意,如果在returnPointer函数中声明stFoo为局部变量,则在返回此函数后它将不再存在。为避免这种情况,您可以将stFoo声明为全局变量。