之前有在板上贴了尝试使用指标存放不同维度的阵列的程式码
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.把 * 加上括号跟没加差在哪?