C ++代码中的错误指针错误

bad pointer error in c++ code

下面是向图形添加顶点的代码:

void myGraph::addVertex(const string &newVertex)
{
    if (getIndex(newVertex) != -1)
    {
        std::cout << ("addVertex: ");
        std::cout << newVertex;
        std::cout << (" failed -- vertex already exists.") << std::endl;
        return;
    }

    // if array of vertices is full, we need to expand it and 
    // also expand Edges
    if (sizeof(Vertices)/sizeof(Vertices[0])==numVertices)
    {
        Vertices = resize(Vertices, 2*numVertices + 1);
        Edges = resize(Edges, 2*numVertices + 1);
    }

    Vertices[numVertices++] = newVertex;

}

这里是调整顶点数组大小的代码:

string *myGraph::resize(string array1[], int newSize)
{

    // make array of size equal to new size
    string *temp = new string [newSize];
    int smallerSize = newSize;
    // if the size of input array is less than the new size then smaller size will be that of input array
    if (sizeof(array1)/sizeof(array1[0]) < smallerSize)
    {
        smallerSize = sizeof(array1) / sizeof(array1[0]);
    }
    // loop till smaller size and copy the content of input array to newly created array
    for (int i = 0; i < smallerSize; i++)
    {
        temp[i] = array1[i];
    }

    return temp;
}

当我调试这段代码时,它只添加了 1 个顶点,即 numVertices=1,下一步它在 Vertices[numVertices++]

中说

sizeof 给出了指向数组中数据的指针的大小,而不是数组的总大小。这取决于您的平台,但很可能 sizeof(string*)/sizeof(string)(相当于您的大小计算)总是 return 1。您可能应该使用 std::vectorstd::list 为此,正确的选择取决于您将如何使用它。这些标准容器 类 将为您分配内存和调整大小,因此您不必担心。

您可以通过将旧数组大小传递给调整大小来修复它:

string *myGraph::resize(string array1[], int array1Size, int newSize)

然后:

if (array1Size < smallerSize) {
   smallerSize = array1Size ;
}

正如 Katie 解释的那样,代码中的 sizeof(array1) 不是实际数组的大小,您应该使用 string* array1 来明确它是指向堆上已分配内存的指针