简体   繁体   English

初始化二叉搜索树中的字符串数组

[英]initializing array of string in binary search tree

my node contains an int and a string variable, and I tried using binary search tree. 我的节点包含一个int和一个字符串变量,我尝试使用二进制搜索树。 the code is as follow: 代码如下:

struct node{
int a;
string members[5];
};

int main(){
node * root = NULL;
root = (node*)malloc(sizeof(node));
root->members[0] = "aaaaa";
return 0;
}

of course, my code wasn't exactly like that, I made it short in main because I want to show just the problem. 当然,我的代码并非完全如此,我在主要部分中做了简短说明,因为我只想展示问题。 it gave me 'access violation writing location'. 它给了我“访问冲突写入位置”。 I tried using 'new node();' 我尝试使用'new node();' instead of malloc and that didn't happen. 而不是malloc,但这并没有发生。 why is this exactly? 这到底是为什么呢?

malloc() only allocates memory. malloc()仅分配内存。 It doesn't call the constructor of the object. 它不调用对象的构造函数。 You could call the constructor on allocated memory using, eg 您可以使用以下方法在分配的内存上调用构造函数:

void* mem = malloc(sizeof(node));
if (mem) {
    node* root = new(mem) node;
    // ...
}

When using new node instead of malloc(sizeof(node) the allocate memory also gets initialized. Using an uninitialized object is undefined behavior. 当使用new node而不是malloc(sizeof(node) ,分配内存也会被初始化。使用未初始化的对象是未定义的行为。

malloc only allocates raw storage. malloc仅分配原始存储。 new allocates raw storage and initializes it to contain a specified type. new分配原始存储并将其初始化为包含指定的类型。

If you're allocating only POD types, that distinction is mostly one of wording, with little real difference in what happens. 如果仅分配POD类型,则该区别主要是措辞之一,而发生的事情几乎没有真正的区别。

If you're allocating something like an std::string that has a constructor, there's a world of difference though. 如果您要分配一个带有构造函数的类似std::string东西,那么会有很大的不同。 If you use new , then your string variables have all been initialized so they're real (albeit, still empty) strings. 如果您使用new ,那么您的string变量都已初始化,因此它们是真实的(尽管仍然为空)字符串。 When you just use malloc , they haven't been initialized at all--they're just chunks of uninitialized raw storage the right size to contain a string . 当您仅使用malloc ,它们根本没有被初始化-它们只是未初始化的原始存储块,其大小合适以包含string When you try to use them as a string, a quick crash is about the best you can hope for. 当您尝试将它们用作字符串时,快速崩溃几乎是您所希望的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM