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

后端 未结 13 2158
[愿得一人]
[愿得一人] 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:17

    You can't pass arrays to functions.

    If you really wanted to print the size, you could pass a pointer to an array, but it won't be generic at all as you need to define the array size for the function as well.

    #include 
    
    void PrintSize(int (*p_anArray)[10]);
    
    int main(void) {
        int myArray[10];
        printf("%d\n", sizeof(myArray)); /* as expected 40 */
        PrintSize(&myArray);/* prints 40 */
    }
    
    void PrintSize(int (*p_anArray)[10]){
        printf("%d\n", (int) sizeof(*p_anArray));
    }
    

提交回复
热议问题