Reputation: 1671
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();
Upvotes: 5
Views: 8277
Reputation: 450
It is legal, as already noted in the other answers. You could even rewrite your data.c
to this:
#include "data.h"
static struct person person;
person * getPersonInfo()
{
return &person;
}
This will return a pointer to your structure in data memory, without any need to allocate it first on the heap. The static
keyword is just about the scope of your symbol person
(local to data.c) but the data itself is valid global in your program.
Upvotes: 1
Reputation: 106012
Line
static struct person* person_p = NULL;
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.
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.
Upvotes: 5
Reputation: 19864
person_p
is a variable whose scope is just for the file data.c
as it is a static variable. You are using this variable to allocate some memory on heap and return the address to main.c
and there is a variable which holds this value in main.c i.e. pointer
.
So here you are not returning the variable but the value the variable is holding which is totally fine because even if the variable goes out of scope the value returned(i.e. address) is still valid which is on heap.
Upvotes: 1