0

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;
    }
}
Moriarity
  • 25
  • 6

3 Answers3

2

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.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
2

Your code has undefined behaviour because variable N was not initialized with the number of potential elements of the array when it was used to allocate the array in the heap

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

That is as a global variable with the static storage duration it was assigned 0 by the compiler. According to the C++ Standard

When the value of the expression is zero, the allocation function is called to allocate an array with no elements.

Rewrite your code at least like

#include <ioStream>
using namespace std;

struct point{
    int x;
    int y;
};

int main(){
    int N;

    cin>>N;
    point *p = new point[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;
    }
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

If you know the maximum number of points, better do something like:

const int MAXN = 1000;
Point p[MAXN];

int N;
cin >> N;
// ...

You can manually allocate space as well but you should read N first.

cin >> N;
Point *p = new Point[N];
// ...

A third option is to use a container (vector for dynamic arrays).

vector<Point> p;
cin >> N;
while(N--)
{   int x, y;
    cin >> x >> y;
    Point p_(x, y); // Assumes constructor exists
    p.push_back(p_);
}
mrk
  • 3,061
  • 1
  • 29
  • 34
  • The third option is new to me. p.push_back() is quite usefull, I can use that in other programs too. Thanks .. – Moriarity Oct 06 '14 at 16:59
  • You are welcome, you can use a reference to learn these things. Google cppreference. You can also vote up my answer if it did help :) – mrk Oct 06 '14 at 17:01