C++: sizeof for array length

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

sizeof array / sizeof array[0]

When I make a new array of size 23, shouldn't I get 23 back for LengthOf?

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

Why does len == 4?

UPDATE: I made a typo, it's a WCHAR*, not a WCHAR**.


Solution 1:

Because str here is a pointer to a pointer, not an array.

This is one of the fine differences between pointers and arrays: in this case, your pointer is on the stack, pointing to the array of 23 characters that has been allocated elsewhere (presumably the heap).

Solution 2:

WCHAR** str = new WCHAR[23];

First of all, this shouldn't even compile -- it tries to assign a pointer to WCHAR to a pointer to pointer to WCHAR. The compiler should reject the code based on this mismatch.

Second, one of the known shortcomings of the sizeof(array)/sizeof(array[0]) macro is that it can and will fail completely when applied to a pointer instead of a real array. In C++, you can use a template to get code like this rejected:

#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;
}