Basic program help

I'm new to c++ programming and I am in Computer Science. I was wanting to figure out why my previous assignment kept giving me an unhandled exception. Any help would be appreciated but please don't suggest stuff far more complicated as I haven't gotten to that point yet. Here is the code.

I couldn't change any of the prototypes I believe my objects array was the problem. I am still a bit hazy on pointers.

#include <iostream>
#include "graph1.h"

using namespace std;

//Prototypes
void getData(int* no_points, int* x, int* y, int* r, int* g, int* b);
int* drawPolyLine(int* x, int* y, int no_points);
void colorPolyLine(int* objects, int no_points, int r, int g, int b);

int main()
{
//variable declaration
const int MAX_POINTS = 10;
char repeat = 'y';
int no_points = 0;
int r = 0;
int g = 0;
int b = 0;
int x[MAX_POINTS];
int y[MAX_POINTS];
int *objects = 0;

//repeat program if desired
do
{
//function to get data
getData(&no_points, x, y, &r, &g, &b);

//function to drawpolyline
objects = drawPolyLine(x, y, no_points);

//function to color polyline
colorPolyLine(objects, no_points, r, g, b);

//program re runnability
cout << "Would you like to run the program again (Y/N)? ";
cin >> repeat;

} while (repeat == 'y' || repeat == 'Y');

}

void getData(int* no_points, int* x, int* y, int* r, int* g, int* b)
{
//variable declaration
int i = 0;

do
{
cout << "Enter # of points: ";
cin >> *no_points;
} while (*no_points < 3 || *no_points > 10);


do
{
cout << "Enter r/g/b color (between 0 and 255 inclusively): ";
cin >> *r >> *g >> *b;
} while (*r < 0 || *r > 255 && *g < 0 || *g > 255 && *b < 0 || *b > 255);

for (i = 0; i < *no_points; i++)
{
cout << "Enter x/y coord for Point #" << i+1 << ": ";
cin >> *x >> *y;
}


}

int* drawPolyLine(int* x, int* y, int no_points)
{
//variable declaration
int objects[10];

for (int f = 0; f < no_points - 1; f++)
{
objects[f] = drawLine(x[f], y[f], x[f + 1], y[f + 1], 1);
}
return(objects);
}

void colorPolyLine(int* objects, int no_points, int r, int g, int b)
{
//variable declaration
int j = 0;

for (j = 0; j < no_points - 1; j++)
{
setColor(objects[j], r, g, b);

}

}
Do you know when you get the unhandled exception? A debugger would allow you to step through your code and add break points so you can see where the problem is.

I suspect your problem is with the return value from drawPolyLine. The function declares an array on the stack and then returns a pointer to the array. However, as soon as the function returns, the array is out of scope and invalid.

I think you need to dynamically allocate the array (using new) and then deallocate the array when you are done using it (using delete) after calling colorPolyLine.

By the way, if you edit your post and put code tags around your code, it will be easier for us to read and comment on. Just highlight you code and click the Format button that looks like "<>".
Topic archived. No new replies allowed.