簡體   English   中英

C ++字符串復制錯誤到結構指針數據字段

[英]c++ String copying error to struct pointer data fields

我目前正在編寫一個使用二進制搜索樹存儲名稱和電話號碼(基本上是電話簿)的程序。 之前,我已經使用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 *根,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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM