#include <iostream> using namespace std; int main(int argc, char const *argv []){ int M = 5; int n = 5; // 聲明數組行指針 char * a[M]; for (int i = 0; i < M; i++) { // 聲明數組列指針 a[i] = new char[n]; // 列賦值 for (int j = 0; j < n; j ++){ a[i][j] = j; } } // 打印值 for (int i = 0; i < M; i++){ for (int j = 0; j < n; j++){ printf("%d ", a[i][j]); } printf("\n"); } // 打印行指針 printf("a[0] : %p\n", a[0]); printf("a[0] : %p\n", *(a+0)); // 打印具體位置指針 printf("a[0][0]: %p\n", *(a+0)+0); printf("a[0][3]: %p\n", *(a+0)+3); // 值的打印方法 printf("a[1][2]: %d\n", *(*(a+1)+2)); printf("a[1][2]: %d\n", a[1][2]); // delete 內存 for (int i = 0; i < M; i++){ delete [] a[i]; } return 0; }
#include <iostream> using namespace std; int main(int argc, char const *argv []){ int rowsNum = 5; int columnsNum = 5; // 兩維都不知道 char **a; a = new char * [rowsNum]; for (int i = 0; i < rowsNum; i++) { a[i] = new char [columnsNum]; for (int j = 0; j < columnsNum; j++) { a[i][j] = j; printf("%d ", a[i][j]); } printf("\n"); } printf("%d\n", sizeof(a)); for (int i = 0; i < rowsNum; i++) { delete [] a[i]; } delete [] a; return 0; }
多說一句:new和delete要注意配對使用,即有多少個new就有多少個delete,這樣才能夠避免內存泄漏!