多维数组,指针数组使用,指向指针的指针

创建多维数组,并差创建数组指针进行操作

View Code
#include <stdio.h> 

int main(int argc, char **argv) {

int shape1[5][3] = {1,0,0,
1,0,0,
1,0,0,
1,0,0,
1,0,0};

int shape2[5][3] = {0,0,0,
0,0,0,
0,1,1,
1,1,0,
0,1,0};

typedef int (*shapes_p)[3];
shapes_p shapes[2] = { shape1, shape2 };

shapes[0][1][0] = 5;
shapes[1][1][0] = 5;

printf("shape1[1][0] == %d\n", shape1[1][0]);
printf("shape2[1][0] == %d\n", shape2[1][0]);

}

shape1和shape2的类型其实为int * shape1[5];

int *p=shape[0];

P+7=1;//等于shape[1][2]=1

要创建一个指针数组,指向int* [5];

typedef int (*shape_p)[5];

shape_p shapes[2];

对于一维数组,使用T *ptr指向即可,对于二维数组,使用T (*ptr)[size]指向行数为size的二维数组
 对于上面的例子,还可以如下设定

int(*shapes[])[3]={ shape1, shape2 };

shapes[1][3][0]指向shape2的第三行第一列.

shapes            // 类型为"int (*x[2])[3]" (也就是 "(**x)[3]") 

shapes[1]         // 类型为"int (*x)[3]" 

shapes[1][3]      // 类型为"int x[3]" (也就是 "int *x") 

shapes[1][3][0]   // 类型为"int x"

#include <stdio.h>
int main() 
{ 
    int a[]={1,2,3,4,5}; 
    int b[]={2,2,3,4,5}; 
    int c[]={3,2,3,4,5}; 
    int *p[3]={a,b,c}; //指针数组,数组元素为指向int的指针
    int i; 
    for(i=0;i<3;i++) 
        printf("%d - %s\n",*p[i],&p[i]); 
    //getch(); 
return 0;
} 
/*
如果是int *p[]={a,b,c}; 
output:
1 - ��P���P���P�
2 - ��P���P�
3 - ��P�
如果是int *p[3]={a,b,c}; 
1 - ��A���A���A�
2 - ��A���A�
3 - ��A�
*/

  

char**Data[70]={NULL};

一个包含70个指向char指针的指针数组

分配70*sizeof(char**)比特的空间,也就是70*4=280比特空间

View Code
char **Data[70]={NULL}; 
char **ptr, **ptr2, **ptr3;

ptr = (char **) malloc(sizeof(char *));
*ptr = "Hello, world";
Data[0] = ptr;

ptr2 = (char **) malloc(sizeof(char *));
*ptr2 = "Goodbye, cruel world";
Data[2] = ptr2;

ptr3 = (char **) malloc(10 * sizeof(char *));
Data[4] = ptr3;

ptr3[0] = "Message 0";
ptr3[1] = "Message 1";
...
ptr3[9] = "Message 9";

printf("%s\n", *Data[0]);
printf("%s\n", Data[2][0]);
printf("%s\n", Data[4][0]);
printf("%s\n", Data[4][1]);
...
printf("%s\n", Data[4][9]);

char*Data2[10][70]={NULL};

指向char*指针的二维数组,分配的空间为10*70*sizeof(char*)=2800比特

参考:http://stackoverflow.com/questions/1015944/how-does-an-array-of-pointers-to-pointers-work

LED淘宝旗舰店: http://shop61500599.taobao.com/

posted @ 2012-01-01 16:46  lxk613  阅读(420)  评论(0编辑  收藏  举报