正在初始化指向数组c++的指针

Initializing pointer to array c++

本文关键字:c++ 指针 数组 初始化      更新时间:2023-10-16

我是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";

当然,这个代码片段是无效的,因为它覆盖了并没有为代码对象保留的内存。