Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: sizeof for array length

Tags:

c++

macros

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**.

like image 332
Nick Heiner Avatar asked Nov 28 '22 19:11

Nick Heiner


2 Answers

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).

like image 176
Mark Rushakoff Avatar answered Dec 10 '22 18:12

Mark Rushakoff


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;
}
like image 36
Jerry Coffin Avatar answered Dec 10 '22 17:12

Jerry Coffin