Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return a Pointer-To-Array from a function in C?

Pointers-to-array (not array pointers) are a lesser-known feature of the C programming language.

int arr[] = { 3, 5, 6, 7, 9 };
int (*arr_ptr)[5] = &arr;

printf("[2]=%d", (*arr_ptr)[2]);

They allow you to "un-decay" a dynamically allocated array pointer.
(which is pretty cool in my opinion)

int *ptr = malloc(sizeof(int) * 5);
int(*arr_ptr)[5] = (int(*)[5])ptr;

printf("[2]=%d", (*arr_ptr)[2]);

I’m trying to define a function to return an array pointer, without success.
I tried something like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int (*)[5] create_arr_5(void) 
{
    int(*arr_ptr)[5] = malloc(sizeof(int) * 5);
    return arr_ptr;
}

>Solution :

The function should be defined like this:

int (*create_arr_5(void))[5]
{
    int(*arr_ptr)[5] = malloc(sizeof(int) * 5);
    return arr_ptr;
}

Talking through the declaration, create_arr_5 is a function:

create_arr_5()

That takes no parameters:

create_arr_5(void)

And return a pointer:

*create_arr_5(void)

To an array of size 5:

(*create_arr_5(void))[5]

Of int:

int (*create_arr_5(void))[5]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading