how sizeof() works in pass by reference arguments

后端 未结 6 1718
深忆病人
深忆病人 2021-01-22 04:56

I passed a array to function and tried to find the length of the array . but the result was not expected . can anybody explain please?

int main()
{
     int arra         


        
相关标签:
6条回答
  • 2021-01-22 05:27

    You have to remember that arrays decays to pointers. That means that in the function func the variable arr is not actually an array but a pointer. And doing sizeof on a pointers returns the size of the pointer and not what it points to.

    You get the result 2 because you're on a 64-bit system where pointers are 64 bits (i.e. 8 bytes), an when divided by the size of int (which is 4 bytes) you get the result 2.

    0 讨论(0)
  • 2021-01-22 05:39

    sizeof() operator returns the size of the data type. here int size is two.

    0 讨论(0)
  • 2021-01-22 05:41

    Seems to me that the result is caused because sizeof(arr) == 8 (size of a pointer on your PC) and sizeof(arr[0]) == 4 because it is an integer hence 8/4==2.

    This declaration: void func(int arr[]) tells the function to expect a pointer to int as argument.

    It is not clear to me whether is possible to calculate the sizeof an array by reference. C functions accepting array reference as arguments always tend to receive their length too as argument.

    The difference with main() function is that inside main array variable is of type int[10], thus sizeof is able to get its length in bytes. In func, arr is of type int* so sizeof gives you only the length in bytes of a pointer.

    0 讨论(0)
  • 2021-01-22 05:44

    When you pass an array into a function as a parameter, the array decays into a pointer to the beginning of the array. A pointer has no meta information stored in it unlike the array. A good practice is to pass the size to the function as an additional parameter.

    void func(int *arr, int size);
    

    Here's what C standard says (C99 6.3.2.1/3 - Other operands - Lvalues, arrays, and function designators):

    Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue

    So, once you pass it to the function - Inside the function, it's no more an array, it's a pointer.

    0 讨论(0)
  • 2021-01-22 05:46
    sizeof(arr)
    

    is the size of a pointer, not the size of the block arr points to.

    0 讨论(0)
  • 2021-01-22 05:52

    You are sending and recieving a array pionter, not the array.

    while sending arg::

    func(array[10]);
    

    While Receiving arg:

    void func(int array[10])
    

    But it's not good to send the total array. So send and receive arguments like below.

    func(array, arry_size);  //function call
    void func(int array[], int length)  //defin
    
    0 讨论(0)
提交回复
热议问题