I have bug when calling to a function dynamic_arr – somehow I loose all my array and only
the first element being returned.
In my code my main calls a function that dynamically needs to create an array
and after the user will insert the elements of the array all the array needs to be passed to
function funcdosomthing.
But at the moment function funcdosomthing gets only the first element and not all the array.
Just to make clear that everything else works – when I don’t use function dynamic_arr and
set the array manualy int a[] = {1, 0, 2}; everything works fine and function funcdosomthing gets all the array with 3 elements.
Here’s my code:
int *dynamic_arr(int n)
{
int i, *a;
a = (int*)calloc(n, sizeof(int));
for(i=0;i<n;i++) scanf("%d",a+i);
return a;
}
int mainprograma()
{
int n,*a,i;
scanf("%d",&n);
a=dynamic_arr(n);
funcdosomthing(a, sizeof a / sizeof a[0]);
...
You are trying to calculate the size of an array from a pointer to a dynamic array.
In C you simply cannot find out the length of an array if you only have a pointer to the array. The code you are using is appropriate if you have an array, but you don’t have an array, you have a pointer.
So, if you had declared
alike thisor this
then
awould be an array rather than a pointer and thesizeofcode above would be applicable.Fortunately you know how big the dynamic array is because you just created it. It has
nelements. So you must write your call tofuncdosomthinglike this: