Why isn't the size of an array parameter the same as within main?

后端 未结 13 2108
[愿得一人]
[愿得一人] 2020-11-21 04:13

Why isn\'t the size of an array sent as a parameter the same as within main?

#include 

void PrintSize(int p_someArray[10]);

int main () {
           


        
相关标签:
13条回答
  • 2020-11-21 05:18

    As others have stated, arrays decay to pointers to their first element when used as function parameters. It's also worth noting that sizeof does not evaluate the expression and does not require parentheses when used with an expression, so your parameter isn't actually being used at all, so you may as well write the sizeof with the type rather than the value.

    #include <stdio.h>
    
    void PrintSize1 ( int someArray[][10] );
    void PrintSize2 ( int someArray[10] );
    
    int main ()
    {
        int myArray[10];
        printf ( "%d\n", sizeof myArray ); /* as expected 40 */
        printf ( "%d\n", sizeof ( int[10] ) ); /* requires parens */
        PrintSize1 ( 0 ); /* prints 40, does not evaluate 0[0] */
        PrintSize2 ( 0 ); /* prints 40, someArray unused */
    }
    
    void PrintSize1 ( int someArray[][10] )
    {
        printf ( "%d\n", sizeof someArray[0] );
    }
    
    void PrintSize2 ( int someArray[10] )
    {
        printf ( "%d\n", sizeof ( int[10] ) );
    }
    
    0 讨论(0)
提交回复
热议问题