Re: [問題] struct&string問題
※ 引述《jeffreyshe (jeffrey)》之銘言:
: 最近在寫二元搜尋樹
: 有一個bug百思不得其解
: 下面是每個node的struct
: typedef struct student
: {
: unsigned int sid;
: unsigned int score;
: struct student*llink,*rlink;
: string name;
: }NodeType;
這個類別不是 POD( Plain Old Data ) type, 以一個 auto物件來
說, 配置的過程類似這樣:
1. {
2. char memory[ sizeof(NodeType) ];
3. NodeType &student = *reinterpret_cast<NodeType*>( memory );
4.
5. // 呼叫成員 name 的建構子
6. new ( &student.name ) std::string( "hello" );
7.
8. assert( student.name == "hello" );
9. assert( student.name.length() == 5 );
10 }// 結束 scope 時自動呼叫 student.name.std::string::~string()
: 在insert一個node之後 發現樹的走訪一直有問題
: 後來發現是name的問題
: NodeType student;
: student.rlink=NULL;
: student.llink=NULL;
: cin>>student.name;
: cout<<student.name; <--正常
: BST.Insert(&student); <--Insert的最後一行也有印出正常的name
: cout<<BST.root->score<<BST.root->name;(因為只有一個,就用root去讀了..)
: score數值正常,後面就overflow了...測過length()高達2萬多...
假如 std::string內含兩個成員 str & len, str 指向一塊動態配
置的記憶體, len 則是紀錄該記憶體已儲存的字元數, 以上面的例
子來說, 在第 4行以後, 你都可以存取 :
std::string::str
std::string::len
沒有問題, 但是如果要存取 *str, 則要到第 7行之後(才有配置好
的記憶體可用), 不過在離開 scope之後, 你什麼東西都不能用!
: 把string換成char name[50]就正常了,50是隨意打的,測資的name只有打abc...
應該是湊巧, 因為離開 scope記憶體也是被回收了. 我不太相信你
只有在這個地方試著去印 root 指的內容.
: 不知道問題出在哪裡?
: 編譯器是dev c++
型態跟物件同名是哪招?
--
▂▅▂ ▁ ● ◣ 朴 ☆ 素 ★ 妍 ◢
◢ ◣ ◢▂▂◣ ◢▂※◣ ◢▄▂◣ T.T.L Listen 2
★ ★ ★ ★ ▉ ★ ★▏▉ ★ ★◣ http://ppt.cc/jIUk
◥ˇ◢ ▃◥ˇ◤▃ ◥ˇ◤ ◥ˇ◤◢ 說什麼結束
▃▃▇▃▃ ◢▇◣ ▋▎ ▋¥▎ ◢ http://ppt.cc/zQtB
▼ ▼ ▼ ▼ ψ髮箍 ◤ ◣
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.121.197.115
※ 編輯: loveme00835 來自: 140.121.197.115 (04/21 11:14)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):