Search code examples
carrayssizeof

Using sizeof function in c


I want to write a function in c which is able to print the array we created. However, there is a problem. When I want to create the loop I need to know the number of elements in the array. So, I used the sizeof function in order to fix that.

I wrote the line size = sizeof(list) / sizeof(list[0]); in order to get the size of the whole array and divide it to size of one element in order to get the number of elements in the array. However, when I build the code I get the following warning:

warning : 'sizeof' on array function parameter 'list' will return the size of 'int *'

#include <stdio.h>

void displayArray(int myarray[]);

int main()
{
    int list1[] = {0, 5, 3, 5, 7, 9, 5};
    displayArray(list1);
    return 0;
}

void displayArray(int list[])
{
    int size;
    size = sizeof(list) / sizeof(list[0]);
    printf("Your array is: ");
    for (int i = 0; i < size; i++)
    {
         printf("%d ", list[i]);
    }
    printf("\n");
    return;
}

Solution

  • There's no such thing as array parameters. They're just hidden pointers.

    You should size your array in the caller (where there's a real array) and pass the size to the callee.

    (As arrays get passed to callees, their size information gets lots in the array-to-pointer conversion, and so you have to pass it separately)

    #include <stdio.h>
    
    void displayArray(int myarray[], int size);
    
    int main()
    {
        int list1[] = {0, 5, 3, 5, 7, 9, 5};
        displayArray(list1, sizeof list1 / sizeof list1[0]);
        /*you don't need the parens if the argument is a variable / isn't a type */
        return 0;
    }
    
    void displayArray(int list[], int size)
    {
        printf("Your array is: ");
        for (int i = 0; i < size; i++)
        {
             printf("%d ", list[i]);
        }
        printf("\n");
        return;
    }