指向C++中的结构的指针
Pointers to structures in C++
为了完成我的作业,我必须在C++中实现一个列表,因此我定义了一个结构:
struct Node {
int value;
Node * next;
Node * operator [] (int index)//to get the indexed node like in an array
{
Node *current = this;
for (int i = 0; i<index; i++)
{
if (current==NULL) return NULL;
current = current->next;
}
return current;
}
};
当我将其与实际结构一起使用时,它工作正常:
Node v1, v2, v3;
v1.next = &v2;
v2.next = &v3;
v3.value = 4;
v3.next = NULL;
cout<<v1[2]->value<<endl;//4
cout<<v2[1]->value<<endl;//4
cout<<v3[0]->value<<endl;//4; works just as planned
cout<<v3[1]->value<<endl;//Segmentation fault
但是当我尝试将其与指针一起使用时,事情变得一团糟:
Node *v4, *v5, *v6;
v4 = new Node;
v5 = new Node;
v6 = new Node;
v4->next = v5;
v4->value = 44;
v5->next = v6;
v5->value = 45;
v6->next = NULL;
v6->value = 4646;
//cout cout<<v4[0]->value<<endl; compiler says it's not a pointer
cout<<v4[0].value<<endl;//44
cout<<v4[1].value<<endl;//1851014134
cout<<v4[2].value<<endl;//45
cout<<v4[3].value<<endl;//1851014134
cout<<v4[4].value<<endl;//4646
cout<<v4[5].value<<endl;//1985297391;no segmentation fault
cout<<v6[1].value<<endl;//1985297391;no segmentation fault even though the next was NULL
delete v4;
delete v5;
delete v6;
虽然可以使用函数,但我有一些问题:
- 为什么指针示例中的返回值是结构而不是指针?
- 为什么元素现在有双倍索引,它们之间的元素是什么?
- 为什么没有分段错误?
如果有人向我解释这些时刻或给我可以学习的来源,我将不胜感激
那是因为v4[0]
(和其他人)实际上并没有调用您的Node::operator[]
。那是因为v4
不是一个Node
,它是一个Node*
,指针在operator[]
:v4[i] == *(v4 + i)
后面有一个内在的含义(也就是说,我们只是索引到那个"数组"中)。所以当你写像v4[3]
这样的东西时,那不是在召唤operator[](3)
......相反,它会在内存中的某个地方v4
后给你一个Node
三Node
秒,这基本上只是垃圾。
要获得您想要发生的事情,您必须先取消引用指针:
(*v4)[0]
(*v6)[1]
// etc
通过这样做
v4 = new Node;
cout<<v4[0].value<<endl;//44
cout<<v4[1].value<<endl;//1851014134
cout<<v4[2].value<<endl;//45
cout<<v4[3].value<<endl;//1851014134
cout<<v4[4].value<<endl;//4646
cout<<v4[5].value<<endl;//1985297391;no segmentation fault
您不是在调用结构节点的 operator[],而是在进行指针取消引用,v4[1]
等于 ++v4; *v4;
因此,此代码会导致不可预测的行为,因为您正在取消引用一些垃圾。要使其按预期工作,您需要将其更改为:
cout<<v4->operator[](0).value<<endl;
cout<<v4->operator[](1).value<<endl;
cout<<v4->operator[](2).value<<endl;
...
相关文章:
- 如何在 C# 中映射双 C 结构指针?
- C++:映射结构中的结构指针
- C++:添加新结构时,结构指针向量中的所有元素都会更新
- 类的静态结构指针声明在C++
- 在两个.cpp文件之间定义全局类/结构指针
- 返回对常量结构(指针类型)成员的引用:明显的左值到右值转换
- 是否可以将无符号字符数组reinterpret_cast到仅包含C++中无符号字符成员的结构指针
- 如何在地图中使用结构指针
- 结构指针在"新"调用上给出已分配的地址?
- 铸造结构指针指向C 的工会指针
- c++ 结构指针在初始化为 NULL 时无法读取内存
- 函数中的结构指针的地址为0x1
- C 用结构指针初始化结构
- C 结构指针铸成数组Interop C#
- 方法中不允许访问结构指针
- 如何打印出结构指针
- MPI_Op_create:候选功能不可行.自定义结构指针不能解释为空指针
- 尝试将结构指针传递给类时出错
- 初始化结构指针的值
- 使用 pybind11 将自定义结构(指针向量)从 C++ 传递到 python 的方法是什么?