1

In this code, I'm dereferencing an element that is uninitialized. Are my results undefined?

int x[10];
int *p = x;

cout << sizeof(p) / sizeof(*p) << endl;

2 Answers2

5
cout << sizeof(p) / sizeof(*p) << endl;

is perfectly legal and but not exactly valid code. sizeof is evaluated at compile time. If they can't be evaluated at compile time, you will get compiler error.

The surprise will be the expected result. You won't get 10. To get 10, you'll need to use:

cout << sizeof(x) / sizeof(x[0]) << endl;
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • @Slava, unfortunate but true. – R Sahu Feb 17 '16 at 19:11
  • @MajorasCoffee, that is correct. Since `sizeof` is evaluated at compile time, the only thing that matters is the type of the object, not whether it has a valid value. – R Sahu Feb 17 '16 at 19:13
  • @MajorasCoffee that's fine. Problem is what you trying to achieve dividing size of pointer to size of int. That barely means anything for you. – Slava Feb 17 '16 at 19:14
  • @Slava Originally I thought I was right in thinking that it would result in 4/4 but I like to double check my answers so I looked up the exercise and some guy has that the result is undefined so I was unsure. Thanks for the help! –  Feb 17 '16 at 19:19
  • @MajorasCoffee The result is implementation defined. `sizeof(pointer)` changes depending on what system you are on. Typically it is 4 on a 32 bit system and 8 on a 64 bit system. Maybe that is what was meant by undefined. – NathanOliver Feb 17 '16 at 19:26
1

In c++, the expressions "*p" and "p[0]" evaluate the same way, so:

*p == p[0]

would evaluate to true. I don't know what you mean by "an element that doesn't exist".

I don't think your code does what you think. The line

cout << sizeof(p) / sizeof(*p) << endl;

will evaluate sizeof(p), which is of type int*, and give something like 4, evaluate sizeof(*p), which is of type int, and give something like 4, and then divide them to give 1.

This code is perfectly valid, but since most common systems use 4 bytes for both ints and pointers, you will most likely print out "1" every time.

If you instead wrote:

cout << sizeof(x) / sizeof(*x) << endl;

or

cout << sizeof(x) / sizeof(x[0]) << endl;

you would get "sizeof(int[10]) / sizeof(int)", which equals 10. This is because the type of x is not int*, but int[10], or "an array of 10 ints".

As answered by R Sahu, sizeof() evaluates at compile-time, so if it can't figure out the size, your code will not compile.

Kyle A
  • 928
  • 7
  • 17
  • Originally I thought I was right in thinking that it would result in 4/4 going by my book but I like to double check my answers so I looked up the exercise I was on and some guy has that the result is undefined so I was unsure. Thanks for the help :) –  Feb 17 '16 at 19:23