gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:20:04 25 4
gpt4 key购买 nike

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

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) (相当于您的大小计算)总是返回 1。您可能应该使用类似std::vectorstd::list 为此,正确的选择取决于您将如何使用它。这些标准容器类将为您分配内存和调整大小,因此您不必担心。

关于c++ - C++代码中的错误指针错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27967519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com