分类: LINUX
2010-09-08 15:17:47
本人的基础不太好,对指针经常犯晕,写点实例供备忘;
指针网上学习资料:
#include
#include
#include
#define ARRAY_ROW 5
#define ARRAY_COL 6
void fun1( int c, char ** input )
{
//指针的指针
printf( "fun1-- \n");
char ** cur = input;
for( int i = 0; i < c; i++ )
printf( " cur[%d]:[%s] \n", i, *(cur++) );
printf( "---- \n");
cur = input;
for( int i = 0; i < c; i++ )
printf( " cur[%d]:[%s] \n", i, cur[i] );
}
void fun2( int c, char input[][ARRAY_COL] )
{
//一维数组指针
char (*pa)[ARRAY_COL];
pa = &input[0];
for( int i = 0; i < c; i++ )
printf( " input[%d]:[%s] \n", i, input[i] );
for( int i = 0; i < c; i++ )
printf( " input[%d]:[%s] \n", i, input[i] );
for( int i = 0; i < c; i++ )
printf( "file[%s]line[%d]--> &input[%d]:[%s]\n", __FILE__, __LINE__, i, *pa++ );
for( int i = 0; i < c; i++ )
printf( "file[%s]line[%d]--> &input[%d]:[%s]\n", __FILE__, __LINE__, i, pa[i] );
}
void fun3( int c, char (*input)[ARRAY_COL] )
{
//一维数组指针
printf( "fun3-- \n");
for( int i = 0; i < c; i++ )
printf( " input[%d]:[%s] \n", i, *input++ );
}
void fun4( int RowInput, int ColInput, void * input )
{
//二维数组指针
typedef char DPOINTER[RowInput][ColInput] ;
DPOINTER * ptrA;
ptrA = (DPOINTER*)(input);
for( int i = 0; i < RowInput; i++ )
for( int j = 0; j < ColInput; j++ )
printf( "file[%s]line[%d]--> (*ptrA)[%d][%d]:[%d]\n",__FILE__, __LINE__, i, j, (*ptrA)[i][j] );
}
void fun5()
{
//一、二维数组指针
//访问数组中的字母 'r'
char b[4][3][2] = {{{'a', 'b'}, {'c', 'd'}, {'e', 'f'}},
{{'g', 'h'}, {'i', 'j'}, {'k', 'l'}},
{{'m', 'n'}, {'o', 'p'}, {'q', 'r'}},
{{'s', 't'}, {'u', 'v'}, {'w', 'x'}}};
char (*pa)[2] = &b[1][0];
char (*ppa)[3][2] = &b[1];
printf( " pa[%c] \n", (*(pa+5))[1] );
printf( " ppa[%c] \n", (*(ppa+1))[2][1] );
}
int main( int argc, char * argv[] )
{
char a[ARRAY_ROW][ARRAY_COL]= { "ABCDE", "FGHIJ", "LMNOP", "QRSTU", "VWXYZ" };
char *ptrA[5];
for( int i = 0; i < 5; i++ )
ptrA[i] = (a[i]);
//指针的指针
fun1( 5, ptrA );
//一维数组指针
fun2( 5, a );
//一维数组指针
fun3( 5, &a[0] );
//二维数组指针
char * B = new char[31];
memset( B, 0, 31 );
//赋值
for( int i = 0; i < 30; i++ )
*(B+i) = i+0;
for( int i = 0; i < 30; i++ )
printf( "file[%s]line[%d]-->======================== B+%d:[%d]\n",__FILE__, __LINE__, i, *(B+i) );
fun4( 5,6, B );
//一维、二维数组指针
fun5();
delete[] B;
}