Jen Jen - 1 month ago 8
C Question

How to return dynamic array from void function in c?

I want to return a dynamic array by reference from a void function.
I already searching 3 hours for the answer, couldn't find anything helpfull.
Here is my simplified code :

main()
{
int **a;

xxx(&a);

printf("%d\n\n", a[1]);

}

void xxx(int **a)
{
int i;

*a = (int*)malloc(5 * 4);

for (i = 0; i < 5; i++)
a[i] = i;
printf("%d\n\n", a[1]);
}


I just want to allocate dynamic array in the "xxx" Function and return it by reference to main, than I want to print it or use it for something else. Thanks in advance :)

edit

#include <stdio.h>
#include <stdlib.h>
#define MACROs
#define _CRT_SECURE_NO_WARNINGS

void xxx(int **a);


int main(void)
{
int *a;

xxx(&a);

printf("%d\n\n", a[1]);
}


void xxx(int **a)
{
int i;

*a = malloc(5 * sizeof(**a));

for (i = 0; i < 5; i++)
a[i] = i;
printf("%d\n\n", a[1]);
}

Answer

In your main(), you need to have a pointer, not a pointer to pointer. change

  int **a;

to

 int *a;

and, inside the xxx(), change

 a[i] = i;

to

(*a)[i] = i;

That said