C ++: sizeof for array length

Let's say I have a macro named LengthOf(array):

sizeof array / sizeof array[0]

When I create a new array of size 23, should I not return 23 for LengthOf?

WCHAR* str = new WCHAR[23];
str[22] = '\0';
size_t len = LengthOf(str); // len == 4

Why len == 4?

UPDATE : I made a typo, this WCHAR*, not WCHAR**.

+3
source share
5 answers

Because strthere is a pointer to a pointer, not an array.

This is one of the subtle differences between pointers and arrays: in this case, your pointer is on the stack, pointing to an array of 23 characters that was allocated elsewhere (presumably a bunch).

+12
source
WCHAR** str = new WCHAR[23];

, - pointer to WCHAR a pointer to pointer to WCHAR. , .

-, sizeof(array)/sizeof(array[0]) , . ++ :

#include <iostream>

template <class T, size_t N>
size_t size(T (&x)[N]) { 
    return N;
}

int main() { 
    int a[4];
    int *b;

    b = ::new int[20];

    std::cout << size(a);      // compiles and prints '4'
//    std::cout << size(b);    // uncomment this, and the code won't compile.
    return 0;
}
+11

, , . , , , .

++- , typesafe ( , , ), .

"" , , - .

, C ( , - , ):

, #ifdef __cplusplus, , ++- C-, ++ .

0

, sizeof . , , WCHAR*. , sizeof (WCHAR *) 4. , WCHAR foo[23], sizeof(foo), WCHAR[23], , sizeof(WCHAR) * 23. WCHAR* WCHAR[23] , , new WCHAR[23] WCHAR[23], WCHAR*, .

Like corellary, since it sizeof(new WCHAR[23])is 4 on your platform, you are obviously dealing with an architecture where the pointer has 4 bytes. If you built it on the x64 platform, you will find that it sizeof(new WCHAR[23])returns 8.

0
source

You wrote:

WCHAR* str = new WCHAR[23];

if 23 means a static value (not a variable for the entire life of your program), it is better to use #define or const than just hardcoding 23.

#define STR_LENGTH 23
WCHAR* str = new WCHAR[STR_LENGTH];
size_t len = (size_t) STR_LENGTH;

or C ++ version

const int STR_LENGTH = 23;
WCHAR* str = new WCHAR[STR_LENGTH];
size_t len = static_cast<size_t>(STR_LENGTH);
0
source

All Articles