1. Where are these zeros coming from? How can I change the code to lose them?
It's a coincidence that the values look like your values times 10. If you change your 5 values to anything else, you will still get the same output. The output is actually the total size of the array (20 bytes) times 1, 2, 3, 4 and 5. Indexing off of the array pointer like arr[i] (with indices 1 to 5) causes that. Instead you need to use it like (*arr)[i] (and the indices should be 0 to 4). But there are more problems than just that.
2. The compiler warns me that I'm returning an address to the array, am I to manually relinquish the memory of the array? Is this a closure?
No, it is not a closure. Do you not know what local variables are? You can't return the address of a (non-static) local variable from a function since they are stored on the stack and aren't reliably accessible after the function returns since the stack space will be reused.
3. Is this a good way of going about returning an array from a function? What are some alternative methods?
The closest thing to your code that works is to declare the array as static so it's not stored on the stack and remains accessible after the function returns.
Code:
#include <stdio.h>
int (*getArray())[5] {
static int arr[5] = {2, 5, 6, 8, 10};
return &arr;
}
int main() {
int (*arr)[5]= getArray();
for (int i = 0; i < 5; i++) // indices are 0 to 4
printf("%d ", (*arr)[i]); // must access it like this
putchar('\n');
return 0;
}
But that's overkill since almost the same thing can be achieved more simply like this:
Code:
#include <stdio.h>
int *getArray() {
static int arr[5] = {2, 4, 6, 8, 10};
return arr;
}
int main() {
int *arr = getArray();
for (int i = 0; i < 5; i++)
printf("%d ", arr[i]);
putchar('\n');
return 0;
}
However, that's not how it would usually be done. There are two usual ways to return an array:
1. Dynamically allocate the array and return that.
Code:
#include <stdio.h>
#include <stdlib.h>
int *getArray(int size) {
int *a = malloc(size * sizeof *a);
for (int i = 0; i < size; i++)
a[i] = i * 2;
return a;
}
void printArray(const int *a, int size) {
for (int i = 0; i < size; i++)
printf("%d ", a[i]);
putchar('\n');
}
int main() {
int *a = getArray(10);
printArray(a, 10);
free(a); // remember to free the memory
return 0;
}
b. Declare the array in the caller and pass it in.
This is often the best way.
Code:
#include <stdio.h>
#include <stdlib.h>
void fillArray(int *a, int size) {
for (int i = 0; i < size; i++)
a[i] = i * 2;
}
void printArray(const int *a, int size) {
for (int i = 0; i < size; i++)
printf("%d ", a[i]);
putchar('\n');
}
int main() {
int a[10];
fillArray(a, 10);
printArray(a, 10);
return 0;
}