Reputation: 5071
The following code works, but is it well defined?
const int N = 8;
int arr[N];
int* ptr = arr;
for(int i=0; i<N; i++) {
std::cout << ptr[i] << "\n";
}
and a second question:
running this code with -O2 optimizations compiled as C++14 http://cpp.sh/7eagy gives me the following output:
1
0
0
0
4196448
0
4196198
0
wherease the following version:
const int N = 8;
int arr[N] = {};
int* ptr = arr;
for(int i=0; i<N; i++) {
std::cout << ptr[i] << "\n";
}
gives
0
0
0
0
0
0
0
0
indicating that without the = {} arr was not zero initialized, but according to https://en.cppreference.com/w/cpp/language/zero_initialization it should be
at least the given example states: double f[3]; // zero-initialized to three 0.0's
so what's the reason I'm not getting zeros in the first version?
Upvotes: 3
Views: 95
Reputation: 238411
is it well defined to cast a static array to a pointer and then incrementing this pointer to access the elements?
Yes, this is well defined.
The following code works, but is it well defined?
No, that code is not well defined.
You default initialise the array which has automatic storage, not static. The values of the trivially constructible elements are indeterminate. You read those indeterminate values. The behaviour of the program is undefined.
so what's the reason I'm not getting zeros in the first version?
Because you didn't zero-initialise the array in the first version.
Upvotes: 2
Reputation: 11430
In the first version, you have
int arr[N];
instead of, second version:
int arr[N] = {};
It has nothing to do with the pointer access. The page you link says:
double f[3]; // zero-initialized to three 0.0's
but that is true only for static variables. Yours is a local, non-static, variable (we don't see the full code, but as it is at the same scope as a for
, we can infer it). In standardese, it's written as:
- For every named variable with static or thread-local storage duration that is not subject to constant initialization, before any other initialization.
Upvotes: 3
Reputation: 9068
Jeffrey has given you three quarters of an answer. I'll make it more complete.
The first example you define an array but you don't initialize the values. In the second example, you actually initialize it to zero.
So in the first example, your array contains random values, whatever is sitting on the stack space. And that's why your example is working oddly.
I'd initialize the array and your first example should work fine.
Upvotes: 1