JoeyParis
JoeyParis

Reputation: 27

Array size is being reduced when passed to a function for unkown reasons

I am trying to find the number of elements in an array inside of a function (outside the main() function). Part of that process is finding the size of the array in bytes, but when I get the size of the array after it has been passed to a function it is 4 bytes less than it should be.

This is a stripped down version of my code that print out the size of the array in the main function and then prints out the size of the array that has been passed to the function. These sizes should be the same but that is not the case.

#include <stdio.h>

int main()
{
    // Initialize variables
    int numbers[3];

    // Request user to input an integer 3 times
    int i ;
    for(i = 0; i < 3; i++)
    {
        printf("Please enter an integer: ");
        scanf("%d", &numbers[i]);
    }

    // Print size of array outside of function
    printf("Size of numbers: %d\n",sizeof(numbers)); // Prints "12"

    // Get size of array in function
    printf("Size of n: %d\n", debug(numbers)); // Prints "8"

    // End main loop function
    return 0;
}

int debug(int n[])
{
    // Return the size of the array inside the function
    return(sizeof(n));
}

This code outputs:

Size of numbers: 12
Size of n: 8

Any idea what could be causing this problem? It always reports 4 less bytes than it should be.

Upvotes: 1

Views: 715

Answers (2)

Ned
Ned

Reputation: 957

The 8 in the function debug is the number of bytes in the 64-bit address for the beginning of the array. Arrays are passed to functions by their address. C does not carry the size of the array along with its address. That must be passed around separately.

Upvotes: 2

Ed Swangren
Ed Swangren

Reputation: 124642

You cannot truly pass arrays to (or return them from) functions, they degrade to pointers to the first element. Your second sizeof is actually sizeof int*, not sizeof int[3]

Upvotes: 2

Related Questions