指向类似树的班级指针的指针
pointer to array of pointers in Tree-like class
本文关键字:指针 更新时间:2023-10-16
我在C/C 中的指针有一个主要问题。我正在尝试用节点实现类似树状的结构。每个节点都有指向其他节点的另一个指针的指针。
这是我的节点结构:
struct Node
{
int key_value;
bool is_init = false;
Node* children;
};
我的问题似乎在这些行中的某个地方
bool flag = false;
Node *temp = &(root->children[mod]);
while (!flag)
{
mod = key % k;
if (temp->children[mod].is_init != false)
{
if (temp->children[mod].key_value != key)
{
temp = &(temp->children[mod]);
continue;
}
else
{
printf("%d exsistn", key);
return;
}
}
else
{
temp->children = new Node[k];
temp->children[mod].is_init = true;
temp->children[mod].key_value = key;
flag = true;
}
}
通过阅读错误消息,我认为这是因为根级以下的孩子没有指向其他节点数组。
任何帮助都将不胜感激。
该代码对于查找错误不完整。您可能需要将结构修改为类似的东西,以跟踪分配的结构数量:
struct Node
{
int key_value;
bool is_init = false;
Node* children;
int len;
};
并在此处添加检查:
if (temp->len > mod && temp->children[mod].is_init != false)
{ ...
}
我认为您创建新节点的方式是错误的。您只有在找不到temp->children[mod].is_init != false
而不是在null时创建新的节点数组。在现有条件应修复之前可能进行无效检查。
或
temp = &(temp->children[mod]);
在将孩子分配给临时
开始...
更改:
struct Node
{
int key_value;
bool is_init = false;//illegal initialization in C
Node* children;
};
to:
struct Node
{
int key_value;
bool is_init;
Node* children;
};
typedef struct Node NODE;
然后您可以这样创建和初始化:
int main(void)
{
NODE *head = {0}, *first = {0}, *temp = {0};
head = malloc(sizeof(NODE));
head->key_value = 10;
head->is_init = 0;
if(first != 0)
{
temp->children = head;
temp = head;
}
else
{
first = temp = head; //save location of first item
}
// etc., etc.
// ...
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么++(*p)更改指针值
- 调整大小后指向元素值的指针unordered_map有效?
- 正在将指针转换为范围
- 使用指向成员的指针将成员函数作为参数传递
- 将OpenCV C++重写为EmguCV C#-如何使用指针
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错