gpt4 book ai didi

c++字符串复制错误到结构指针数据字段

转载 作者:行者123 更新时间:2023-11-28 02:23:12 24 4
gpt4 key购买 nike

我目前正在编写一个程序,该程序使用二叉搜索树来存储姓名和电话号码(基本上是电话簿)。我以前用 AVL 树做过这个,它工作正常。我决定为这个实现切换我的方法,而不仅仅是复制/粘贴最后一个的逻辑和格式。在这样做的过程中,我遇到了一个奇怪的错误,我不知道为什么会这样。起初我以为我的问题出在我返回结构指针的方式上,但实际上是在我的字符串复制中。

我写了一个非常基本的程序,它只显示了返回结构的复制函数,然后用它递归地用数据(从文件中读入)填充 BST。

这里是简化的例子:

#include <iostream>
#include <string>

using namespace std;

struct Node
{
std::string first;
std::string last;
std::string phone;
};

Node* copyfunc(std::string first, std::string last, std::string phone)
{
Node* temp = NULL;

temp->first = first;
temp->last = last;
temp->phone = phone;

return temp;
}

int main()
{
std::string first, last, phone;
first = "Jenny";
last = "Something";
phone = "8675309";

Node* newStruct = NULL;

newStruct = copyfunc(first, last, phone);

cout << newStruct->first << endl;
cout << newStruct->last << endl;
cout << newStruct->phone << endl;

cout << "Never to be seen again..." << endl;

return 0;
}

现在,我尝试使用 VS2013 调试器找出问题所在,它发生在第一个拷贝上:“temp->first = first;”。它中断访问冲突警告,然后打开 xstrings(标题?)并指向该部分:(第 2245 行)

if (this->_Myres < _Newsize)
_Copy(_Newsize, this->_Mysize); // reallocate to grow"

我只是在猜测,但据我所知,在我看来它无法创建新字符串以适应旧字符串的长度。

程序(包括示例程序和真实程序)将编译,它们只是在达到复制功能时挂起。

感谢所有意见,谢谢!

编辑:我对我的结构使用指针的原因是我使用的算法的编写方式。 BST 中实际将节点链接在一起的函数接受 Node* 类型而不是 Node 对象。例如:recursiveInsert(Node* root, Node* newNodeToAdd);

最佳答案

在您尝试使用它之前,您没有将 temp 初始化为任何有用的东西。

Node* temp = NULL;

temp->first = first; // oops! temp is NULL!

完全放弃指针会更容易:

Node copyfunc(std::string first, std::string last, std::string phone)
{
Node temp = {first, last, phone};
return temp;
}

您还应该考虑通过 const 引用而不是值来传递参数。或者完全放弃该功能并在需要的地方初始化 Node:

Node newStruct = {first, last, phone};
cout << newStruct.first << endl;

关于c++字符串复制错误到结构指针数据字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31567904/

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