C51學(xué)習(xí)心得體會(huì),指針和數(shù)組在程序設(shè)計(jì)中的關(guān)系
C語言中的指針和數(shù)組幾乎可以互換,數(shù)組名可認(rèn)為是一個(gè)常量指針,指針可用來完成涉及數(shù)組下標(biāo)的操作。
e.g.int * nPtr;
int Array[size];
(1)數(shù)組與指針等價(jià)
nPtr = Array;或者nPtr = &Array[0];
(2)引用數(shù)組元素Array[3]
nPtr[3]或者*(nPtr+3)或者*(Array+3)
其中,nPtr[3]為指針下標(biāo)表示法。
(3)e.g.數(shù)組拷貝
//用數(shù)組表示法把s2拷貝到s1中
void copy1(char *s1,constchar *s2)
{
int i
for(i=0;s1[i]=s2[i];i++);
}
//用指針表示法把s2拷貝到s1中
void copy1(char *s1,constchar *s2)
{
for(;* s1=* s2;s1++,s2++);
}
(4)指針數(shù)組
char * suit[4]={"zhonghua","renmin","gonghe","guojia"};
//char * 表示suit數(shù)組的每一個(gè)元素都是指向char類型的指針,即suit數(shù)組中存儲(chǔ)的是4個(gè)指針。
//等價(jià)于 char suit[4][9]={"zhonghua","renmin","gonghe","guojia"};
//二維數(shù)組必須設(shè)置相同的列數(shù),因此指針數(shù)組更具有靈活性。
(5)數(shù)組指針
int a[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};
int (*p)[4];
p=a;
*(*(p+i)+j);//表示a[i][j]的值
void search(float (*p)[4],int n);//多維數(shù)組的指針作為函數(shù)參數(shù)
search(a,2);//函數(shù)調(diào)用
(6)指向指針的指針
e.g. main()
{
char *name[]={"Beijing","Chongqing","Shanghai","Tianjin","Shijiazhuang"};
char **p;
int i;
for(i=0;i<5;i++)
{ p=name+i;
printf("%sn",*p);//如果是**p,表示一個(gè)字符。
}
}
舉例:洗牌和發(fā)牌程序
#include
#include
#include
void shuffle(int [][13]);//為什么參數(shù)中數(shù)組的第二個(gè)下標(biāo)必須有
void deal(const int [][13],const char * [],const char * []);
main()
{
int deck[4][13]={0};
constchar * face[4]={"Hearts","Diamonds","Clubs","Spades"};//指針數(shù)組
constchar * suit[13]={"one","two","three","four","five","six","seven",
"eight","nine","ten","eleven","twelve","theteen"};
srand(time(NULL));
shuffle(deck);
deal(deck,face,suit);* face[4]和* suit[13]數(shù)組必須定義成const,否則在此出現(xiàn)錯(cuò)誤,
//錯(cuò)誤類型:不能把“* char[]”轉(zhuǎn)換成“const * char[]”
return 0;
}
void shuffle(int wDeck[][13])
{
int row,col,i;
for(i=1;i<53;i++)
{
row=rand()%4;
col=rand()%13;
while(wDeck[row][col]!=0)
{
row=rand()%4;
col=rand()%13;
}
wDeck[row][col]=i;
}
}
void deal(const int wDeck[][13],const char * wFace[],const char * wSuit[])
{
int i,row,col;
for(i=1;i<53;i++)
for(row=0;row<4;row++)
for(col=0;col<13;col++)
{
if(wDeck[row][col]==i)
printf("%5s of %-8s%c",wFace[row],wSuit[col],i%2==0?'n':'t');
}
}