How to find out the size of a dynamic array.

char * word = "whatever" 

when you call sizeof or how to write on the Internet

 sizeof(word)/sizeof(word[0]); 

always returns 4 for any word. And what is the reason such that you can easily find out the size in bytes of the value, but the size of the array is so difficult to know. I came from java

    2 answers 2

    You do not have an array there, but a pointer to a string. The program is 32-bit, so the size of 4 bytes is returned, that is, the size of the pointer in the 32-bit program. Define an array as

     char word[] = "whatever"; int sz = sizeof(word) / sizeof(word[0]); 

    sz will be equal to 9 (8 letters plus terminating 0).

    By the way, I note that sizeof(word[0] is equal to one — this is the size of an ASCII character. So the formula in this case can be slightly simplified.

    And I also note that your array is not dynamic at all, but the most static one.

    • Whether and I can use an array if the word comes outside in rantayme? maybe it would be worth pointing out in the question - J Mas
    • @J Mas, I did not understand what it means to "come outside at runtime." Is passed as a function argument, is it? In C / C ++, you cannot pass an array to a function. Even if the formal parameter is declared as an array, the pointer is still passed. In C ++, with STL, you can pass array <> or vector <> containers, which represent static and dynamic arrays respectively. - freim

    In this ad

     char * word = "whatever"; 

    it is not an array object that is declared, but an object of a pointer that points to the first character of the string literal. And the pointer size is fixed regardless of whether it points to a scalar object, or to the first element of the array.

    Note that in C ++, string literals have the type of constant character arrays. Therefore, a pointer that points to a string literal must be declared with the const qualifier:

     const char * word = "whatever"; 

    To declare an array, you need to write

     char word[] = "whatever"; 

    Then you can really use the expression sizeof( word ) / sizeof( *word ) to count the elements in the array.

    In the case of arrays, or pointers to arrays containing strings, you can also use the standard strlen function to determine how many characters are in a string (excluding the terminating zero).

    For example,

     #include <cstring> //... char word[100] = "whatever"; size_t n = std::strlen( word ); // n = 8 

    or

     #include <cstring> //... const char *word = "whatever"; size_t n = std::strlen( word ); // n = 8