- 论坛徽章:
- 0
|
这是接上一篇 “多维数组如何在堆中申请明??”的话题。
- 可以先申请足够的空间,然后转换成你所要的任何类型空间。
- #include <stdlib.h>;
- #include <stdio.h>;
- typedef short int int16;
- void *buf;
- int *nInt[5]; //[5][10]
- int16 *nInt16; //[5]
- int init()
- {
- int i;
- buf = malloc( 5*10*sizeof(int)+5*sizeof(int16) );
- if( buf == NULL ) return -1;
- bzero( buf, 5*10*sizeof(int)+5*sizeof(int16) );
- for( i=0; i<5; i++ )
- nInt[i] = buf+10*sizeof(int);
- nInt16 = buf + 5*10*sizeof(int);
- return 0;
- }
- int main()
- {
- int i,j;
- if( init() ){
- printf("Init Error\n");
- return -1;
- }
- printf("Init OK.\n" );
- for( i=0; i<5; i++ ){
- for( j=0; j<10; j++ )
- nInt[i][j] = i*j;
- nInt16[i] = i;
- }
- return 0;
- }
- 这是的二维数组虽然不像直接定义的int Arrary[5][10]那样省内存,而且还要事先初始化,但还是可以将就着就用啦。
- 这种用法在共享内存中经常用到,类型可以为任何类型,如struct等
复制代码 |
|