【问题标题】:c++ String copying error to struct pointer data fieldsc ++字符串复制错误到结构指针数据字段
【发布时间】:2015-10-12 14:38:38
【问题描述】:

我目前正在编写一个程序,它使用二叉搜索树来存储姓名和电话号码(基本上是电话簿)。我以前用 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);

【问题讨论】:

    标签: c++ string struct


    【解决方案1】:

    在尝试使用之前,您没有将 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;
    

    【讨论】:

    • 删除指针的问题是我需要将 Node* 类型传递给从 BST 的根开始的递归函数,并在需要的地方链接新节点。此外,读取数据的函数和递归函数都在一个类中,一个是公共的,一个是私有的。我可以这样做,但我必须重写/重组很多现有代码。
    • @user3857017 好吧,您的帖子中没有任何内容表明您需要使用指针。
    • 公平,我想我不应该假设这是已知的。我用于 BST 的算法来自我的一本书,它使用大量用于添加、删除等的指针来实现 BST。而不仅仅是在读入数据时通过显式赋值来实现。我将编辑 OP 以反映指针的“需求”。
    • 实际上,重写并没有我想象的那么多。感谢您的可靠回答和解释!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    • 2020-11-04
    相关资源
    最近更新 更多