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

后端 未结 13 2107
[愿得一人]
[愿得一人] 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 <stdio.h>
    
    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;
    

    }

    0 讨论(0)
  • 2020-11-21 05:12

    Because arrays decay into pointers when they are passed as parameters. This is how C works, although you can pass "arrays" in C++ by reference and overcome this issue. Note that you can pass arrays of different sizes to this function:

     // 10 is superfluous here! You can pass an array of different size!
    void PrintSize(int p_someArray[10]);
    
    0 讨论(0)
  • 2020-11-21 05:15

    It's a pointer, that's why it's a common implementation to pass the size of the array as a second parameter to the function

    0 讨论(0)
  • 2020-11-21 05:15

    In the C language, there is no method to determine the size of an unknown array, so the quantity needs to be passed as well as a pointer to the first element.

    0 讨论(0)
  • 2020-11-21 05:16

    In c++ you can pass an array by reference for this very purpose :

    void foo(int (&array)[10])
    {
        std::cout << sizeof(array) << "\n";
    }
    
    0 讨论(0)
  • 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 <stdio.h>
    
    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));
    }
    
    0 讨论(0)
提交回复
热议问题