0

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;
}
timi95
  • 368
  • 6
  • 23
  • 2
    You add an argument to the function for the number of elements. – Some programmer dude Oct 24 '16 at 12:30
  • 1
    Also note that in the `main` function, using `&array` gives you something that is of type `int (*)[13]`. Not really the same as the `int *` you want the function to receive. Enable more warnings fromn the compiler if that doesn't already produce a warning. And treat warnings as errors. The good news is that it's simple to fix: Don't use the address-of operator on the array. Using plain `array` will have the array decay to a pointer to the first element (of the correct type). – Some programmer dude Oct 24 '16 at 12:33

2 Answers2

2

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
LPs
  • 16,045
  • 8
  • 30
  • 61
1

The function can't magically know, so it's usually solved something along this:

void myFunc(int *array, int size)
{
    int i;
    for(i=0;i<size;++i)
        array[i] = i;
}

#define ARRSZ(arr) arr, sizeof(arr)/sizeof(*arr)

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

    myFunc( ARRSZ(array) );
    return 0;
}
sp2danny
  • 7,488
  • 3
  • 31
  • 53