How to know the size (in bytes) of a char array passed to a function?

前端 未结 1 1761
清酒与你
清酒与你 2021-01-22 11:37

I am testing the sizeof operator. In two cases in my code, I get the size of the pointer (I think). In the other cases I get

相关标签:
1条回答
  • 2021-01-22 12:09

    When an array is passed to a function, what's actually happening is that a pointer to the first element in the array is being passed. Put another way, the array decays into a pointer to the first element.

    In these two declarations:

    void test (char arrayT[]);
    void test2 (char *arrayU);
    

    arrayT and arrayU are of exactly the same type due to this decay, and sizeof will return the same value for both, i.e. the size of a char *.

    Contrast the above with this:

    char array1[] = "a string";
    char *array2;
    

    Where array1 is actually an array of size 9, while array2 is a pointer whose size (on your system) is 4.

    Because of this, there is no way to know the length of an array passed to a function. You need to pass in the size as a separate parameter:

    void test (char arrayT[], size_t len);
    
    0 讨论(0)
提交回复
热议问题