Problem in declaring array size inside a function
I'm passing an array (pointer) as an argument of a function, but I know the size of the array only inside the function, so I'd need something like this:
Code:
#include <stdio.h>
void foo(int *vec)
{
int n = 3;
vec = malloc(n*sizeof(int));
vec[0] = 41;
vec[1] = 10;
vec[2] = 47;
printf("vec[1]: %d", vec[1]);
}
int main()
{
int *vec;
foo(vec);
printf("vec[1]: %d", vec[1]);
getch();
return 0;
}
The first printf gives me the right output, but the second one seems to crash the program. If I knew the size of the array before executing the function I would use int vec[n] to declare the array and delete the malloc line, but unfortunately that's not the case.
Any ideas?
Thanks.