【发布时间】:2015-08-17 18:16:24
【问题描述】:
我有一个关于 C 函数如何返回静态变量的问题:
在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()可以这样使用吗:person* pointer = getPersonInfo();
【问题讨论】:
-
Do not cast the return value of
malloc(),这里的static跟作用域有关,sotrage对于全局变量来说总是static的。 -
这是什么意思“这个上下文中的静态与范围有关,对于全局变量来说,sotrage总是静态的”
-
在函数内使用
static意味着该变量具有static存储类,这导致它保留了对函数的调用,static在文件范围内意味着你不能externalize 变量/函数到不同的.c文件。 -
static关键字影响 2 件事,可见性(取决于链接)和生命周期。使用static声明具有全局范围的变量是多余的。 -
函数
getPersonInfo()返回一个指针person_p保存值(malloc的返回值,副作用为person_p)。