正在初始化指向数组c++的指针
Initializing pointer to array c++
我是C++的新手。请参阅以下代码:
//sample1
int arr[2] = { 11, 22 };
int(*t)[2];
t = &arr;
cout << *t[0] << "n";
cout << *t[1] << "n";
//sample2
int arr2[2];
arr2[0] = { 33 };
arr2[1] = { 44 };
int(*t2)[2];
t2 = &arr2;
cout << *t2[0] << "n";
cout << *t2[1] << "n";
//sample3
int arr3[2];
arr3[0] = { 55 };
arr3[2] = { 66 };
int(*t3)[2];
t3 = &arr3;
cout << *t3[0] << "n";
cout << *t3[1] << "n";
//输出
11
-858993460
33
-858993460
55
66
有人能告诉我如何初始化指向数组的指针吗示例3超出了我的理解范围。
您的代码有两个问题:
1) []
的优先级高于*
,因此在所有这些情况下都需要括号(cfr.operator优先级)。如果你不使用它们,你将对每个2个整数的数组进行指针运算(因此立即超出范围),例如
int(*t)[2]; // A pointer to an array of 2 integers
cout << t[0]; // The address of the array
[first_integer][second_integer] ... garbage memory ...
^
cout << t[1]; // The address of the array + sizeof(int[2])
[first_integer][second_integer] ... garbage memory ...
^
cout << *t[0]; // Dereference at the address of the array
cout << *t[1]; // Dereference past the end of the array
// ---- correct -----
cout << (*t)[0]; // Dereference the pointer to the array and get the element there
[first_integer][second_integer] ... garbage memory ...
^
cout << (*t)[1]; // Dereference the pointer to the array and get the second element there
[first_integer][second_integer] ... garbage memory ...
^
2) 您在线路上有一个超范围访问
arr3[2] = { 66 };
这就是你应该如何进行:
//sample1
int arr[2] = { 11, 22 };
int(*t)[2];
t = &arr;
cout << (*t)[0] << "n";
cout << (*t)[1] << "n";
//sample2
int arr2[2];
arr2[0] = { 33 };
arr2[1] = { 44 };
int(*t2)[2];
t2 = &arr2;
cout << (*t2)[0] << "n";
cout << (*t2)[1] << "n";
//sample3
int arr3[2];
arr3[0] = { 55 };
arr3[1] = { 66 };
int(*t3)[2];
t3 = &arr3;
cout << (*t3)[0] << "n";
cout << (*t3)[1] << "n";
初始化很好。
数组与指针几乎是一样的:
int arr[2] = { 11, 22 };
int * t;
t = arr;
cout << t[0] << "n";
cout << t[1] << "n";
在这个代码片段中
//sample3
int arr3[2];
arr3[0] = { 55 };
arr3[2] = { 66 };
int(*t3)[2];
t3 = &arr3;
cout << *t3[0] << "n";
cout << *t3[1] << "n";
定义了一个具有两个元素的数组。此数组元素的索引的有效范围为0, 1
在本声明中,
arr3[2] = { 66 };
由于索引2无效,有人试图将数据写入数组之外。所以你有
arr3: | 55 | uninitilaized | 66 |
index: 0 1 beyond the array
在这些陈述之后,
int(*t3)[2];
t3 = &arr3;
指针t3指向数组arr3,
表达式
t3[0]
给出阵列arr3
表达式
*t3[0]
给出数组的第一个元素。因此陈述
cout << *t3[0] << "n";
输出55。
表达式
t3[1]
指向数组arr3之后的内存。你在这个地址写了66。所以这个值是由语句输出的
cout << *t3[1] << "n";
当然,这个代码片段是无效的,因为它覆盖了并没有为代码对象保留的内存。
相关文章:
- 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文件中的矢量时出错