读取访问冲突。通过函数指向动态数组的指针

时间:2019-02-23 21:27:55

标签: c++ pointers dynamic-arrays

因此,运行代码时出现访问冲突错误。我正在努力了解点通过函数传递时如何与动态分配的数组一起使用。错误分别位于drawPolyLine函数和colorPolyLine函数的第77行和第89行。这是我的整个程序:

//Alexander Salas
//Lab Test part 2
//Prompts user for number of points for polyline and colors them accordingly.

#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() {
    //pointer declarations
    int* x = NULL;
    int* y = NULL;
    int* objects = NULL;

    //point number variable declarations
    int no_points = 0;

    //color variable declarations
    int r = 0;
    int g = 0;
    int b = 0;

    //function calls
    getData(&no_points, x, y, &r, &g, &b);
    objects = drawPolyLine(x, y, no_points);
    colorPolyLine(objects, no_points, r, g, b);

    //program end
    return 0;
}

//prompts user for number of points, color and x/y coordinates
void getData(int* no_points, int* x, int* y, int* r, int* g, int* b) {

    //dynamically allocates parallel x/y coordinates arrays
    x = new int[*no_points];
    y = new int[*no_points];

    //number of points prompt
    cout << "Enter number of points for polyline: ";
    cin >> *no_points;

    //color prompt
    cout << "Enter r/g/b color: ";
    cin >> *r >> *g >> *b;

    // x/y coordinate loop prompt
    for (int i = 0; i < *no_points; i++) {
        cout << "Enter x/y coordinate for point #" << i + 1 << ": ";
        cin >> x[i] >> y[i];
    }
}

//draws polyline and stores object number in a dynamically allocated array
int* drawPolyLine(int* x, int* y, int no_points) {

    //dynamically allocated object number array
    int* objects = new int[no_points]();

    //initializes graphics window
    displayGraphics();

    //drawLine loop, stores object number into array
    for (int i = 0; i < no_points; i++) {
        objects[i] = drawLine(x[i], y[i], x[i + 1], y[i + 1], 5);//ERROR
    }

    //returns dynamically allocated objects array
    return objects;
}

//colors polyline using dynamically allocated array
void colorPolyLine(int* objects, int no_points, int r, int g, int b) {

    //color loop
    for (int i = 0; i < no_points; i++) {
        setColor(objects[i], r, g, b);//ERROR
    }
} 

同样,该错误发生在第77行和第89行。由于该错误涉及两个单独的动态数组,因此我确定它与我如何分配它们或如何将指针传递给它有关。功能。

这是一次实验室测试,一周前我以惊人的方式失败了,因此您不必担心帮助我作弊。我真的只是想让该程序正常运行,并更好地了解如何通过函数将指针与动态数组一起使用。

此外,根据测试规则,不应更改函数原型及其参数 ,这也是为什么我确定错误与我的行为有关的原因使用指针。

任何帮助将不胜感激,我想在此先感谢您的任何建议!

0 个答案:

没有答案