>
>
>
What is sizeof(&X) expression equal to,…

Andrey Karpov
Articles: 674

What is sizeof(&X) expression equal to, X being defined as "char *X[n];"?

Consider the following sample.

char *(X[64]);
cout << sizeof(&X) << endl;

The question is: what value will be printed? The right answer is "the pointer's size". In particular, it may be number 4 in a Win32 program or 8 in a Win64 program.

The answer above seems obvious, yet there are two subtleties which often cause confusion. Let's examine another sample:

char *(X[64]);
memset(&X, 0, sizeof(&X));

This code is incorrect: we empty only a part of the X array. There are two reasons for such errors.

Reason one

The VS 2005 compiler has an error that causes "sizeof(&X)" to return the array's size. As a result, this code, being built in VS 2005, will correctly empty the whole array. Accordingly, some programmers get misled and consider this code correct. The compiler's error disappears after installing SP1.

By the way, here you are an interesting test on the subject I encountered in the code of Google C++ Mocking Framework:

class TestForSP1 {
private: // GCC complains if x_ is used by sizeof before defining it.
  static char x_[100];
  // VS 2005 RTM incorrectly reports sizeof(&x) as 100, and that value
  // is used to trigger 'invalid negative array size' error. If you
  // see this error, upgrade to VS 2005 SP1 since Google Mock will not
  // compile in VS 2005 RTM.
  static char 
  Google_Mock_requires_Visual_Studio_2005_SP1_or_later_to_compile_[
      sizeof(&x_) != 100 ? 1 : -1];
};

Reason two

The first function's argument is "&X". Actually taking of the address is not necessary here. We are handling the array all the same. That is, the following two records have the same correct result:

memset(&X, 0, sizeof(X));
memset(X, 0, sizeof(X));

This also confuses programmers and they think that sizeof(&X) and sizeof(X) will have the same result too. But it is a mistake.