[英]c++ Unable to initialize array of pointers to null c++
我试图创建一个特里,但当我将数组中的指针初始化为NULL
它将中断程序。 程序完成,但不输出任何内容。 为什么这样做?我看了网上的例子,他们也在做。
class trie
{
private:
struct Node
{
char letter;
Node *children[26];
};
//the beginning of the trie
Node *root;
public:
/* Constructors with No Arguments */
trie(void);
/* Destructor */
~trie(void);
//Function to insert string into the trie.
void insert(string word);
//Function to help insert
void insertHelper(string word, Node * & trieNode);
//Funtion to print the contents of the trie.
void printTrie();
//Function to get the index if a char matches.
int getIndex(char letter);
};
trie::trie()
{
/* Initialize the root of the node */
root = NULL;
for(int i = 0; i < 26; i++){
root->children[i] = NULL;
}
}
trie::trie()
{
root = NULL;
for(int i = 0; i < 26; i++){
root->children[i] = NULL; // you are following the nullptr
}
}
在现代C ++中,应使用nullptr
而不是NULL
。 不,实际上,您应该使用诸如std::shared_ptr<>
和std::unique_ptr<>
或std::vector<>
类的智能指针。
我建议您阅读《 C程序员的十诫》中的 #2:
2:您不应跟随NULL指针,因为混乱和疯狂在其结尾等待着您。
显然,这里的圣经被错误地抄写了,因为这些单词本来应该是``空指针'',以最大程度地减少空指针和宏NULL(其中更匿名)的概念之间的混淆。 否则,含义很简单。 空指针指向充满龙,恶魔,核心堆放物和无数其他肮脏生物的区域,如果您打扰他们的睡眠,所有这些都会在您的程序中嬉戏。 尽管有些亵渎性的旧代码会无端地假定此值,但空指针不会指向任何类型的0。
这里的“跟随NULL指针”是指取消引用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.