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

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

    In 'C' programming languange 'sizeof()' is the operator and he returns the size of the object in bytes.Argument of the 'sizeof()' operator must be a left-value type(integer,float number,struct,array).So if you want to know the size of an array in bytes you can do it very simple.Just use the 'sizeof()' operator and for his argument use the array name.For example:

    #include 
    
    main(){
    
     int n[10];
     printf("Size of n is: %d \n", sizeof(n)); 
    
    }
    

    Output on 32 bit system will be: Size of n is: 40.Because ineteger on 32 system is 4bytes.On 64x it is 8bytes.In this case we have 10 integers declared in one array.So the result is '10 * sizeof(int)'.

    Some tips:

    If we have an array declared like this one 'int n[]={1, 2, 3, ...155..};'. So we want to know how many elements are stored in this array. Use this alghorithm:

    sizeof(name_of_the_array) / sizeof(array_type)

    Code: #include

    main(){

    int n[] = { 1, 2, 3, 44, 6, 7 };
    printf("Number of elements: %d \n", sizeof(n) / sizeof(int));
    return 0;
    

    }

提交回复
热议问题