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

后端 未结 13 2189
[愿得一人]
[愿得一人] 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条回答
  •  旧时难觅i
    2020-11-21 05:04

    So, you will need to pass the lenght of the array as a second parameter. When you are writing code, in which you both declare an array of constant size, and later pass that array to a function, it is a pain to have the array-length constant show up several places in your code...

    K&R to the rescue:

    #define N_ELEMENTS(array) (sizeof(array)/sizeof((array)[0])) 
    

    So now you can do e.g:

    int a[10];
    ...
    myfunction(a, N_ELEMENTS(a));
    

提交回复
热议问题