c函数返回静态变量

rat*_*zip 5 c arrays static pointers

我有一个关于 C 函数如何返回静态变量的问题:

data.h文件中:

#include <stdio.h>
#include <stdlib.h> 

typedef struct
{
   int age;
   int number;
} person;

person * getPersonInfo();
Run Code Online (Sandbox Code Playgroud)

data.c

#include "data.h"
static struct person* person_p = NULL;

person * getPersonInfo()
{
   person_p = (struct person*)malloc(10 * sizeof(struct person));
   return person_p;
}
Run Code Online (Sandbox Code Playgroud)

main.c

#include "data.h"

int main()
{
   person* pointer = getPersonInfo();
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

函数getPersonInfo()返回一个指针,该指针是 中的静态指针data.c,这是允许且合法的吗?在 中main.c,该函数可以getPersonInfo()这样使用吗:person* pointer = getPersonInfo();

hac*_*cks 5

线

static struct person* person_p = NULL;  
Run Code Online (Sandbox Code Playgroud)

person_p声明一个具有静态存储持续时间、文件范围和内部链接的变量。这意味着它只能在文件中通过名称引用data.c,并且内部链接将其共享限制为该单个文件。

静态存储持续时间意味着一旦分配了内存,person_p只要程序运行,它就会保留在相同的存储位置,从而允许它无限期地保留其值。这意味着您可以返回指向该位置的指针。
因此,您的代码是有效且合法的。

  • 但指针被定义为static,仅在data.c中可见 (2认同)