If this:
int out[size];
doesn't appear in file scope (in other words, appears inside a function), it defines a variable with automatic storage duration. This means the variable only exists as long as execution is inside its scope (which is the nearest set of braces). Once the scope is left, the variable is gone.
Returning an array isn't possible in C, return out
instead returns a pointer to the array's first element. So you see the problem: The pointer points to an object that doesn't exist any more.
Now with your code, the first call to printf()
seems to work. This is "by accident" (it's not guaranteed at all), but can be explained: In your implementation, nothing changes the memory where your array was located, until another function (here printf()
) is called and overwrites this memory with its own local variables.
How to do this correctly: There are several possibilities:
- Let the caller provide the array.
- return a pointer to an allocated array using
malloc()
as shown in anoher answer, caller has to free()
it.
- Add a
static
to the array definition, which gives it static storage duration (for the whole execution time of the program), but be aware of a severe consequence of this: there's only one instance of this array forever, creating all sorts of problems, so, better don't.
IMHO, 1. is the most idiomatic C way of doing this, using your original code:
void range(int *out, int start, int end, int step){
int size = (end - start)/step;
for(int i = 0, j = start; i < size; i++, j += step){
out[i] = j;
}
}
int main()
{
int a[5];
range(a, 1, 5, 1);
printf("%i\n", *a);
printf("%i\n", *a);
return 0;
}