之前有在板上貼了嘗試使用指標存放不同維度的陣列的程式碼
http://pastebin.com/d1Vjf9Dj
#include <stdio.h>
int main()
{
int n1[1] = {1}, n2[2][2] = {{211, 212}, {221, 222}}, n3[3][3][3] =
{{{3111, 3112, 3113}, {3121, 3122, 3123}, {3131, 3132, 3133}},
{{3211, 3212, 3213}, {3221, 3222, 3223}, {3231, 3232, 3233}},
{{3311, 3312, 3313}, {3321, 3322, 3323}, {3331, 3332, 3333}}};
int *ptr[] = { n1, *n2, **n3 };
int i, j, k;
printf( "%d\n", *ptr[0] );
for ( i = 0; i < 2; i++ )
for ( j = 0; j < 2; j++ )
printf( "%d %s", *( ptr[1] + 2*i + j ), ( j == 1 ) ? "\n" : "" );
for ( i = 0; i < 3; i++ )
for ( j = 0; j < 3; j++ )
for ( k = 0; k < 3; k++ )
printf("%d %s%s",
*( ptr[2] + 3*3*i + 3*j + k ),
( k == 2 ) ? "\n" : "", ( j + k == 4 ) ? "\n" : "" );
return 0;
}
不過上面的程式碼拿的資料應該是超出陣列範圍的,這樣的程式碼怪怪的,
所以我就把陣列轉型一下,不過又碰到奇怪的問題
http://pastebin.com/umKP07vX
#include <stdio.h>
int main()
{
int n1[1] = {1}, n2[2][2] = {{211, 212}, {221, 222}}, n3[3][3][3] =
{{{3111, 3112, 3113}, {3121, 3122, 3123}, {3131, 3132, 3133}},
{{3211, 3212, 3213}, {3221, 3222, 3223}, {3231, 3232, 3233}},
{{3311, 3312, 3313}, {3321, 3322, 3323}, {3331, 3332, 3333}}};
int *ptr[] = {n1, (int*)n2, (int*)n3};
int i, j, k, n = 0;
printf( "%d\n", *ptr[0] );
for ( i = 0; i < 2; i++ )
for ( j = 0; j < 2; j++ )
printf( "%d %s",
( (int(*)[2])ptr[1] )[i][j], ( j == 1 ) ? "\n" : "" );
for ( i = 0; i < 3; i++ )
for ( j = 0; j < 3; j++ )
for ( k = 0; k < 3; k++ )
printf( "%d %s%s",
( (int(*)[3][3])ptr[2] )[i][j][k],
( k == 2 ) ? "\n" : "", ( j + k == 4 ) ? "\n" : "" );
return 0;
}
我本來是想轉型成陣列的,不過 C 好像不能轉型成陣列,所以就轉成指標了,
不過就像上面的程式碼,如果沒有把 * 括號起來,就會跑出錯誤,錯誤訊息
好像也是說我不能把它轉成陣列,可是加上括號就好了,我不知道為什麼要加
括號,只是看了版上的置底文,跟著做就可以跑了。
我想問的問題是
1.這樣的程式碼是否合理,轉型之後存取的範圍就是正確的?
2.把 * 加上括號跟沒加差在哪?