[英]How to properly read from .txt file and assign to structs with pointer, C++
我正在尝试读取文件并对其进行反序列化。 我一次输入两个字符串并将其分配给一些变量foo
和bar
。 首先foo
被分配给NODE2
和 ofc 位向量,然后bar
被分配给NODE2
,但是当这种情况发生时foo
也被分配给NODE2
。 我怀疑它与指针有关,但我希望struct
NodeReading
有一个指向字符串的指针,以释放我最终将构建的树的空间。 我计划在二叉树中拥有数十万个NodeReadings
。 我只想将字符串存储为指针,因为字符串也会很大。 只有叶子会存储一个实际的字符串(内部节点用于根据它们的位集进行导航)。
#include <iostream>
#include <fstream>
using namespace std;
struct Read {
string dna;
bitset<5> bf;
};
struct NodeReading {
bitset<5> bloom_filter;
string* dna_string;
};
static const string file = "tree.txt";
ifstream ist {file};
//could be a pair return instead of Read, but I like it this way.
Read read_line() {
string a;
bitset<5> b;
ist >> a >> b;
return Read {a, b};
}
NodeReading write_to_tree() {
Read s = read_line();
NodeReading hey {s.bf, &s.dna};
return hey;
}
int main {
NodeReading foo = write_to_tree(); //gets assigned NODE1 at first
NodeReading bar = write_to_tree(); //gets assigned NODE2, and then foo also gets assigned NODE2
return 0;
}
树.txt:
NODE1 11110 NODE2 11110
无论发生什么实际上都是未定义的行为。 如果您在这两行之间进行其他处理 - NodeReading foo = write_to_tree();
& NodeReading bar = write_to_tree();
然后尝试访问foo
,那么您的应用程序有可能由于分段错误而崩溃。
在write_to_tree()
内部,您的变量Read s
未在堆上分配,因此,一旦您从该 function 返回,变量Read s
就会从 scope 中消失,并且您丢失了其中的所有数据。 您需要在堆上分配它。
在您的代码struct NodeReading
看起来是多余的。 您可以直接使用struct Read
, struct NodeReading
只是struct Read
的位字段的副本和指向其字符串的指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.