2

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]);
    ...
0

2 Answers 2

8

You are trying to calculate the size of an array from a pointer to a dynamic array.

sizeof a / sizeof a[0]

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 a like this

int a[3];

or this

int a[] = {0, 1, 2};

then a would be an array rather than a pointer and the sizeof code above would be applicable.

Fortunately you know how big the dynamic array is because you just created it. It has n elements. So you must write your call to funcdosomthing like this:

funcdosomthing(a, n);
Sign up to request clarification or add additional context in comments.

Comments

0

Why do you try to find the size when you already know the size?!

You should use n instead of calculating the size like sizeof a / sizeof a[0]. And more over, sizeof(a) will give your expected result iff a is an array. In this case, it is a pointer-to-memory-which-can-store-n-integers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.