c函数返回静态变量 [英] c function return static variable
问题描述
我有一个关于C函数如何返回静态变量的问题:
I have a question about how C function returns static variable:
在 data.h
文件:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int age;
int number;
} person;
person * getPersonInfo();
在 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;
}
在的main.c
#include "data.h"
int main()
{
person* pointer = getPersonInfo();
return 0;
}
功能 getPersonInfo()
返回一个指针,这是在 data.c
静态指针,这是允许的,并法律?在的main.c
,可以在函数 getPersonInfo()
这样使用:人*指针= getPersonInfo();
function getPersonInfo()
returns a pointer which is a static pointer in data.c
, is this allowed and legal? in the main.c
, can the function getPersonInfo()
be used like this: person* pointer = getPersonInfo();
推荐答案
行
static struct person* person_p = NULL;
声明一个变量 person_p
具有静态存储时间,档案范围和内部链接。这意味着,它可以通过名称只在文件中引用 data.c
和内部连接限制了其分享到这一单个文件。
declares a variable person_p
which has static storage duration, file scope and internal linkage. It means that it can be referenced by name only in file data.c
and internal linkage restricts its sharing to this single file.
静态存储时间意味着一旦内存分配给 person_p
只要程序正在运行,将保持在同一存储位置,允许其无限期地保留它的价值。这意味着你可以返回一个指向该位置。结果
因此,您的code是有效和合法。
Static storage duration means once the memory is allocated to person_p
it will stay at the same storage location as long as program is running, allowing it to retain its value indefinitely. It means you can return a pointer to that location.
Therefore, your code is valid and legal.
这篇关于c函数返回静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!