简体   繁体   中英

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

I have a problem when I'm doing my debugging: Xcode gives:

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

I think it's a problem with my dynamic array...

My assignment is to calculate the perimeter of a polygon with points.

So, my program receives points (x and y) to fill an array of Point s, then I made another array, distance , which I fill with all the distances, and then I can calculate the perimeter.

I don't know if it's very clear but I'm a beginner in 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;
}

You never actually allocate any space for the array variable - you are only declaring it and assigning it a nullptr value. Thus, when you later try executing the array[i]=p; you are trying to dereference a null pointer, which causes your EXC_BAD_ACCESS error.

To fix this, you need to allocate the array, once you know what size it is (ie how many sides your polygon has). You should do this in the same way as you allocate the distance array:

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

Of course, you also need to free the memory when you have finished with it:

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

However, as you are using C++, a far better way than using raw pointers and the new operator is to use the Standard Template Library's std::vector container , which takes care of all allocating and freeing operations internally. Here are the relevant 'replacement' lines:

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

Then you don't need the delete[] lines, as the vectors' memory will be released automatically when the vectors go 'out of scope'. Also, you don't need to really change any of your other code, as the std::vector class has a [] operator, which works as you would want it to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM