#include <stdio.h>
extern void print_double_point_address_value_p(int **p, int *p1);
void main(){
int array[3][2] = {10,11,12,13,14,15};
int *array3[2];
int **pa3 =&array3[0];
//int **dp = array;// 這種寫法錯在哪裡?
//int **dp = &array[0];// 這種寫法錯在哪裡?
int *dp1 = array[0];
int **dp = &dp1; 這樣就可以用二重指針訪問二維數組內的元素了
printf("二維數組的首地址: array = %p, &array[0] = %p \n", array, &array[0]);
printf("二維數組的首地址的指向的地址: *array = %p, array[0] = %p \n", *array, array[0]);
printf("[0][0] 對應的值: **array = %d, *array[0] = %d \n", **array, *array[0]);
printf("\n");
printf("test: *array = %d, &array[0] = %d \n", array, &array[0]);
printf("test : dp1 = %d, dp = %d \n", dp1, dp);
int i = 0, j = 0;
for(i=0;i<3;i++){
for(j=0;j<2;j++){
printf("address array = %p \n", &array[i][j]);
}
}
printf("\n");
for(i=0;i<3;i++){
for(j=0;j<2;j++){
printf("value array = %d, \n", array[i][j]);
}
}
printf("\n");
print_double_point_address_value_p(dp,dp1);
}
extern void print_double_point_address_value_p(int **p, int *p1){//兩種訪問方法
int i = 0, j = 0;
for(i=0;i<3;i++){
for(j=0;j<2;j++){
printf("p = %p, p1 = %p, \n", (*p+i*2)+j, (p1+i*2+j));
}
}
printf("\n");
//int[][]分配在連續空間裡,所以可用一個for循環,遍歷全部元素
int* temp = p1;
for(i=0;i<6;i++){
printf("p = %d, \n", *temp++);
// printf("p = %d, \n", *(temp++));// 和*temp++ 表示的一樣,是指針的移動
// printf("p = %d, \n", (*temp)++);//temp指向的值自增
}
}
編譯這個程序,有兩處warning,
main.c: In function ‘main’:
main.c:21: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘int (*)[2]’
main.c:21: warning: format ‘%d’ expects type ‘int’, but argument 3 has type ‘int (*)[2]’
main.c:22: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘int *’
main.c:22: warning: format ‘%d’ expects type ‘int’, but argument 3 has type ‘int **’
由警告可知,array 和&array[0] 是int(*)[2] 型的指針 和int** 型的指針直接肯定不能賦值,所以
//int **dp = array; //int **dp = &array[0]; 這兩種寫法都是不對的,
如果有上面的兩種賦值,編譯時,指針匹配,不會出錯 ,運行時,有時候會出現段錯誤。