[ad_1]
Local variables go out of scope upon return, so you can’t return a pointer to a local variable.
You need to allocate it dynamically (on the heap), using malloc
or new
. Example:
int *create_array(void) {
int *array = malloc(3 * sizeof(int));
assert(array != NULL);
array[0] = 4;
array[1] = 65;
array[2] = 23;
return array;
}
void destroy_array(int *array) {
free(array);
}
int main(int argc, char **argv) {
int *array = create_array();
for (size_t i = 0; i < 3; ++i)
printf("%d\n", array[i]);
destroy_array(array);
return 0;
}
Alternatively, you can declare the array as static, keeping in mind the semantics are different. Example:
int *get_array(void) {
static int array[] = { 4, 65, 23 };
return array;
}
int main(int argc, char **argv) {
int *array = get_array();
for (size_t i = 0; i < 3; ++i)
printf("%d\n", array[i]);
return 0;
}
If you don’t know what static
means, read this question & answer.
[ad_2]