You cannot return arrays from functions. When point()
returns, the local array within this function goes out of scope. This array is created on the stack, and will get destroyed once the function finishes returning. All memory associated with it is discarded, and the returned pointer points to a position on the stack that doesn't exist anymore. You need to instead allocate a pointer on the heap, and return that instead. This allows array
to be shared across your program.
Instead of:
int array[4];
you need to dynamically allocate a pointer using malloc():
int *array = malloc(4 * sizeof(*array)); /* or sizeof(int) */
if (array == NULL) {
/* handle exit */
}
malloc()
allocates requested memory on the heap, and returns a void*
pointer to it.
Note: malloc()
can return NULL
when unsuccessful, so it needs to be checked always. You also need to free() any memory previously allocated by malloc()
. You also don't need to cast return of malloc().
Another thing to point out is using the magic number 4
all over your program. This should really be calculated using sizeof(a)/sizeof(a[0])
.
You can declare this as a size_t
variable in your main()
:
size_t n = sizeof(a)/sizeof(a[0]);
Or you can use a macro:
#define ARRAYSIZE(arr) (sizeof(arr) / sizeof(arr[0]))
And simply call ARRAYSIZE(a)
everytime you want the size of the array.