初始化指向数组C++的指针

问题描述:

我是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超出了我的理解?

+2

这是错误的:'arr3 [2] = {66};' – 2014-10-18 14:45:16

+1

'arr'的初始化没有任何问题。你应该阅读'*'和'[]'运算符的优先级。 (提示:它应该是'(* arr)[0]'等) – 2014-10-18 14:45:43

有两个问题与您的代码:

1)[]有更多的优先级比*所以你需要在所有这些情况下,括号(CFR operator precedence)。如果你不使用它们,你将在每个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"; 

当然此代码段是无效的outputed因为没有为代码的对象保留其覆盖的内存。