Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization of dynamic memory c++

Tags:

c++

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;
}
like image 601
user3665224 Avatar asked Aug 28 '26 02:08

user3665224


1 Answers

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;
}
like image 156
Mohit Jain Avatar answered Aug 30 '26 18:08

Mohit Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!