Search code examples
c++arraysdynamic-memory-allocationgarbage

One of the values in a dynamically allocated array always prints a garbage value


Why is p[1].x printing out to a garbage value? Is it possible to initialize a dynamically allocated array to a given array? If yes, then how?

#include <ioStream>
using namespace std;

struct point{
    int x;
    int y;
};
int N;
point *p = new point[N];
int main(){
    cin>>N;
    for(int i=0; i<N; i++){
        cin>>p[i].x>>p[i].y;
    }
    for(int i=0; i<N; i++){
        cout<<"("<<p[i].x<<", "<<p[i].y<<")"<<endl;
    }
}

Solution

  • On these two lines, you are sizing an array with a variable that is zero initialized (N).

    int N;
    point *p = new point[N];
    

    Therefore, you would be newing an array of length 0. This would lead to problems once you cin>>N because you use that variable to loop and write to the array, which will be writing outside the allocated space.

    These types of cases really beg for std::array or std::vector.