我的动态数组有问题 - 线程 1:EXC_BAD_ACCESS(代码=1,地址=0x0)

Problem with my dynamic array - Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)

我在调试时遇到问题:Xcode 给出:

Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)

我认为这是我的动态数组的问题...

我的作业是用点计算多边形的周长。

所以,我的程序接收点(x 和 y)来填充一个 Points 的数组,然后我制作了另一个数组,distance,我用所有的距离填充它,然后我会计算周长。

不知道说的是否清楚,我是C++初学者

#include <iostream>
#include "Point.h"
#include "Polygone.h"
using namespace std;
int main() {
    int numberSide;
    int x,y;
    Point* array = nullptr;
    Polygone myPolygone;
    cout<<"enter number of sides:"<<endl;
    cin>>numberSide;
    float* distance=new float[numberSide];
    cout<<"enter points:"<<endl;
    for (int i=0; i<numberSide; i++) {
        cin>>x>>y;
        Point p(x,y);
        array[i]=p;
    }
    for (int i=0; i<numberSide-1; i++) {
        distance[i]=array[i].distance(array[i+1]);
    }
    distance[numberSide]=array[0].distance(array[numberSide]);
    myPolygone.perimeter(distance);
    delete [] distance;

    return 0;
}

您实际上从未为 array 变量分配任何 space - 您只是声明它并为其分配一个 nullptr 值。因此,当您稍后尝试执行 array[i]=p; 时,您正在尝试取消引用空指针,这会导致您的 EXC_BAD_ACCESS 错误。

要解决这个问题,您需要分配数组,一旦您知道它的大小(即您的多边形有多少条边)。您应该以与分配 distance 数组相同的方式执行此操作:

    cin>>numberSide;
    float* distance=new float[numberSide];
    Point* array = new Point[numberSide]; // And you should delete the earlier "Point* array = nullptr;` line

当然你也需要在用完后释放内存:

    delete [] distance;
    delete [] array;
    return 0;

但是,当您使用 C++ 时,far 比使用原始指针和 new 运算符更好的方法是使用标准模板库的 std::vector container,它在内部负责所有分配和释放操作。以下是相关的 'replacement' 行:

#include <vector> // This header defines the `std::vector` container
//...
    cin>>numberSide;
    std::vector<float> distance(numberSide);
    std::vector<Point> array(numberSide); 

那么你不需要 delete[] 行,因为向量的内存会在向量进入 'out of scope' 时自动释放。此外,您不需要真正更改任何其他代码,因为 std::vector class 有一个 [] 运算符,它可以按您希望的那样工作。