In below code, I expect 1 to be initialized in all the 10 elements in x array. But, it doesn't seem to be working. May I know what I am missing here?
int main() {
int *x = new int[10];
for(int i =0; i <10; ++i){
*x = 1;
x++;
}
for(int i = 0; i < 10; ++i)
std::cout<<i<<" is "<<x[i]<<std::endl;
return 0;
}
By the time you end the initialization loop, your x is pointing beyond the last allocated element. Before second forloop you need to readjust x to point to start of memory
x -= 10;
Even better would be to keep your walking pointer as a copy
int *xcopy = x;
for(int i =0; i <10; ++i){
*xcopy = 1;
xcopy++;
}
Or use indexing to update the value
for(int i =0; i <10; ++i){
x[i] = 1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With