Can an array be returned from a function in C without using static?
int *func(int n)
{
int d[100];
int i=0,a;
while(n!=0)
{
a=n%2;
d[i]=a;
n=n/2;
i++;
}
return d;
}
Can an array be returned from a function in C without using static?
int *func(int n)
{
int d[100];
int i=0,a;
while(n!=0)
{
a=n%2;
d[i]=a;
n=n/2;
i++;
}
return d;
}
You cant return array that created locally on the stack after exiting from function its not valid anymore. you need to use static array[100] or pointer and malloc memory for it
int *func(int n)
{
static int d[100];
int i=0,a;
while(n!=0)
{
a=n%2;
d[i]=a;
n=n/2;
i++;
}
return d;
}
UPDT:
d
is created with automatic storage duration and references to it will become invalid once it leaves its declaring scope, i.e., when the function returns.
The static
storage instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope.
You will also can use dynamically allocate memory inside the function.
int *func(int n)
{
int *d = malloc(sizeof(int) * (100));
int i=0,a;
while(n!=0)
{
a=n%2;
d[i]=a;
n=n/2;
i++;
}
return d;
}
And dont forget to free allocated memory