0

I'm trying to print an array, however it is only printing one element of the array.

    void printArr(int arr[])
{
    int a;
    for (a = 0; a < _countof(arr); a++)
    {
        printf("%i, ", arr[a]);
    }
}
main()
{
    int nums[] = { 3, 54, 1, 7, 8, 90, 65 };
    printArr(nums);
}

I have figured out that it is because the _countof macro is returning 1, but I have not been able to find a fix for the problem. (I know that I can manually enter the size of array, I want it to work for all arrays.)

  • 2
    You *cannot* find the length of an array just from the pointer which, effectively, was passed. You need to apply that to the array itself - `nums[]` and pass that information to the function too. It gave you `1` because the size of the pointer must have been the same size as the first array element (32-bit compiler). – Weather Vane Jun 21 '21 at 14:35
  • Your `printArr` function doesn't know how big the array it's given is. Arrays passed as function arguments decay to pointers to their first elements. Your compiler should warn you about that. – Adrian Mole Jun 21 '21 at 14:36

0 Answers0