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