總結
對於指針數組的理解:
按照字面意思,首先是指針,其次是數組,就表明這是一個數組,不過數組里面存儲的指針。
```
// 使用指針數組
int **ptr = new int*[4];
for(int i = 0; i < 4; ++i)
{
*(ptr+i) = new int [3];
}
```
如代碼所示:new int * [4],表明這是一個數組,數組里面存儲的是 int *類型的指針。
而等號左值 int ** ptr,首先要看(int *)*ptr ,表明這一個指針,其指向了int *類型的變量。
在看for循環內的內容,這是對數組內指針進行初始化,將數組內的每個指針指向了一個int[3]的數組,
當然這里int [3],也可以改為int[4]等,當然也可以為數組內,每個指針,分別制定不等長的數組。
對於數組指針的理解:
參照一位數組指針的定義
```
int * a = new int [3];
```
和
```
// 使用數組指針
int (*p)[3] = new int [4][3];
printf("數組指針:\np:\t%d\n&p[0]:\t%d\n*p:\t%d\np[0]:\t%d\n&p[0][0]:%d\n\n"
,p,&p[0],*p,p[0],&p[0][0]);
```
等號右值,都是數組,等號左值依然是int *p ,不過因為其實二維數組,所以
在其后,增加了指示二維的[3],以表明,其第二維的維度為3
問題:
對於下面的代碼:
```
class myString;
myString *pStringArray = new myString[13];
```
以下兩種delete有什么區別?
```
delete pStringArray;
delete []pStringArray;
```
方括號的存在會使編譯器獲取數組大小(size)然后析構函數再被依次應用在每個元素上,一共size次。否則,只有一個元素被析構。
博客原文:
http://blog.csdn.net/xietingcandice/article/details/41545119
```
//============================================================================
// Name : TS.cpp
// Author : jiudianren
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <functional>
#include <stdlib.h>
#include <vector>
#include <stdio.h>
using namespace std;
int main()
{
int * a = new int [3];
printf("一維數組:\na:\t%d\n*a:\t%d\n&a[0]:\t%d\n\n"
,a,*a,&a[0]);
// 使用指針數組
int **ptr = new int*[4];
for(int i = 0; i < 4; ++i)
{
*(ptr+i) = new int [3];
}
printf("指針數組一步步申請:\nptr:\t%d\n&ptr[0]:%d\n*ptr:\t%d\nptr[0]:\t%d\n&ptr[0][0]:%d\n\n"
,ptr,&ptr[0],*ptr,ptr[0],&ptr[0][0]);
// 使用數組指針
int (*p)[3] = new int [4][3];
printf("數組指針:\np:\t%d\n&p[0]:\t%d\n*p:\t%d\np[0]:\t%d\n&p[0][0]:%d\n\n"
,p,&p[0],*p,p[0],&p[0][0]);
// 釋放內存
for(int i = 0; i < 4; ++i)
{
delete [] ptr[i]; //注意不要漏掉方括號
}
delete []ptr;
delete []p;
delete []a;
return 0;
}
```
輸出
```
一維數組:
a: 3615416
*a: 3615824
&a[0]: 3615416
指針數組一步步申請:
ptr: 3615440
&ptr[0]:3615440
*ptr: 3615464
ptr[0]: 3615464
&ptr[0][0]:3615464
數組指針:
p: 3615560
&p[0]: 3615560
*p: 3615560
p[0]: 3615560
&p[0][0]:3615560
```