關於這個問題之前有不少人提過,只是換個型式又出現而已。這部份沒有想像中那麼難,只是一樣要拿個紙筆畫一下圖就是了。這次我不多說,大家仔細看範例還有執行結果就知道是要幹嘛的了…
1. 原始碼
// ====================================
// FileName: Ptr1To2.cpp
// Author : Edison.Shih.
// Complier: VC 2008
#include <stdio.h>
#include <stdlib.h>
// ====================================
#define X 2
#define Y 3
#define Z 4
#define ROW 2
#define COL 4
int main(int argc, char **argv)
{
int i=0, j=0, k=0;
int *ptr1 = NULL;
// === 一維陣列 ptr1 表示二維陣列 Array2[ROW][COL]=== //
int Array2[ROW][COL] = {{0,1,2,3}, {4,5,6,7}};
// set the arry , method1
ptr1 = (int*)malloc(sizeof(int)*ROW*COL);
for(i=0; i<ROW; i++){
for(j=0; j<COL; j++){
ptr1[i*COL+j] = Array2[i][j];
}
}
// read the array , method2
for(i=0; i<ROW*COL; i++) printf("ptr1[%d] = %d\n", i, ptr1[i]);
for(i=0; i<ROW; i++){
for(j=0; j<COL; j++){
printf("*(ptr1+%d*COL+%d)=%d\n", i, j, *(ptr1+i*COL+j));
}
}
free(ptr1);
// === 一維陣列 ptr1 表示三維陣列 Array[X][Y][Z]=== //
int Array[X][Y][Z] = {
{ {0,1,2,3},{4,5,6,7}, {8,9,10,11} },
{ {12,13,14,15},{16,17,18,19}, {20,21,22,23} }
};
// set the array, method1
printf("\n");
ptr1 = (int*)malloc(sizeof(int)*X*Y*Z);
for(i=0; i<X; i++){
for(j=0; j<Y; j++){
for(k=0; k<Z; k++){
ptr1[i*Y*Z+j*Z+k] = Array[i][j][k];
}
}
}
// read the array, method2
for(i=0; i<X*Y*Z; i++) printf("*(ptr1+%d)=%d\n", i, *(ptr1+i));
for(i=0; i<X; i++){
for(j=0; j<Y; j++){
for(k=0; k<Z; k++){
printf("ptr1[%d*Y*Z+%d*Z+%d] = %d\n", i, j, k, *(ptr1+i*Y*Z+j*Z+k));
}
}
}
return 0;
}
2. 執行結果
ptr1[0] = 0
ptr1[1] = 1
ptr1[2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