I have a question about how C function returns static variable:
in data.h file:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int age;
int number;
} person;
person * getPersonInfo();
in 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;
}
in main.c
#include "data.h"
int main()
{
person* pointer = getPersonInfo();
return 0;
}
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();
malloc(), static in this context is related to the scope, the sotrage is always static for global variables.staticinside a function means that the variable hasstaticstorage class, which causes that it preserves the value accross calls to the function,staticat the file scope means that you cannotexternalize the variable/function to a different.cfile.statickeyword effects 2 things, visibility (depending on linkage) and lifetime.. Usingstaticfor a variable declared with global scope is redundant.getPersonInfo()returns a pointerperson_pholding value(value of return of malloc, side-effect assing toperson_p).