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];
//std::cout<<"address of x: "<<&x<<std::endl;

for(int i =0; i <10; ++i){
    *x = 10;
    x++;
}

for(int i = 0; i < 10; ++i)
    std::cout<<i<<" is "<<x[i]<<std::endl;

return 0;
}

Dani AI

Generated

The actual problem is pointer loss and undefined behavior. The first loop advances the pointer used for allocation, so by the time the second loop runs that pointer no longer points at the array start (it will be one past the last element). That makes the prints undefined. This directly answers ’s question about where x points at the start of the second loop.

Better approaches:

  • Prefer a container that manages size and lifetime, for example std::vector:
#include <vector>
#include <iostream>

std::vector<int> v(10, 1);
for (size_t i = 0; i < v.size(); ++i)
    std::cout << i << " is " << v[i] << '\n';
  • If a raw array is required, keep the base pointer (or use RAII). Example with a smart pointer:
#include <memory>
#include <iostream>

std::unique_ptr<int[]> a(new int[10]()); // zero-initialized
for (int i = 0; i < 10; ++i) a[i] = 1;
std::cout << a[0] << '\n'; // automatic cleanup

Notes and corrections tied to existing replies: ’s idea of list-initialization is valid in C++11, but a range-based for over a raw int* is not valid, and delete must never be used for memory allocated with new[] (use delete[]). Also remember new int[n] leaves built-ins uninitialized; new int[n]() zero-initializes, and new int[n]{...} performs list-initialization (first elements provided, others zeroed).

Quick checklist: do not increment and lose the original pointer if it’s needed later; prefer std::vector or smart pointers; initialize arrays explicitly if needed; free arrays with delete[] (or let RAII handle it).

Recommended Answers

All 2 Replies

In socratic fashion, I'd ask where does x point at the start of the second loop?

int *x = new int[10]{1,1,1,1,1,1,1,1,1,1}; // missing this: g++ -std=c++11

for(auto &it : x) std::cout << it << " ";

delete x;

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.