timi95 timi95 - 1 month ago 8
C Question

I have something like this code and I would like to know how to get the number of elements of the array I pass in, if there is a way

So int size does not actually give me the size of what I pass in, in the main function. How do I get the exact number of elements in the array that I pass in.

void myFunc(int *array)
{ int size = (sizeof(&array)/sizeof(int));}

int main()
{
int array[]={1,2,3,4,5,6,7,8,9,10,11,12,13};
myfunc(&array);
return 0;
}

LPs LPs
Answer

Pass it as parameter to myFunc.

#include <stdio.h>

void myFunc(int *array, size_t size)
{
    printf("Size = %zu\n", size);

    for (size_t i=0; i<size; i++)
    {
        printf("array[%zu] = %d\n", i, array[i]);
    }
}

int main(void)
{
    int array[]={1,2,3,4,5,6,7,8,9,10,11,12,13};

    myFunc(array, sizeof(array)/sizeof(array[0]));

    return 0;
}
  1. main signature must be int main(void)
  2. sizeof return type size_t so use that type for variables.
  3. You have a typo in your code into main: myfunc should be myFunc