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]);
}
#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]);
}
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
Don't use magic numbers, rewrite your malloc statement like
*a = malloc(5 * sizeof(**a));
to be more robust. Also, for static counts, use #define
MACROs.
Please see this discussion on why not to cast the return value of malloc()
and family in C
..
main()
is not a valid signature for a hosted environment. You need to use int main(void)
, at least.