目录
1. 指针数组的概念
char *color[5];//指针数组定义
int a[100];
int *p = a; //定义一个整型指针,指向数组score的首地址
int *p = &a[0]
指针数组:数组中的每一个元素都是指针类型,用于存放地址。每一个元素都是指针
color[i]中存放的是字符串的首地址,可以用语句
printf("%s\n",color[i])
输出color[i]所指向的字符串。调用printf()函数,以%s的格式输出字符串时,输出参数为地址,从该地址所指定的单元开始连续输出其中的字符,知道遇到'\0'为止。
指针数组在操作时,既可以直接对数组元素进行赋值和引用,也可以间接访问数组元素所指向的单元内容,改变或者引用该单元的内容。(这就是用它的原因吗)
数组指针:定义一个指向数组的指针,这里只有一个指针。
/* 查找奥运五环色的位置,用指针数组实现 */
#include <stdio.h>
#include <string.h>
int main()
{
int i;
char *color[5] = {"red","blue","yellow","green","black"};
/* 指针数组初始化 */
char str[20];
printf("Input a color: \n");
scanf("%s",str);
for(i = 0; i < 5; i++){
if(strcmp(str,color[i]) == 0) break;//str(1,2)1,2可以是字符数组名或字符串常量
}
if(i < 5){
printf("position:%d\n",i+1);
}
else{
printf("Not found\n");
}
return 0;
}
2. 二级指针、二维数组的指针形式、指针数组和二级指针
2.1 二级指针:指向指针的指针
2.2 二维数组的指针形式
首先回顾一下一维数组的指针形式。一维数组名是一个一级指针。
int a[10];
int *p = a;
//int *p = &a[0];
二维数组可以看成多个一维数组构成。二维数组名是一个二级指针。
int a[3][4];
//可以看成是三个一维数组构成,a[0],a[1],a[2]
a = &a[0]
//a[0]本身又是一个一维数组
a[0] = &a[0][0]
//最终表示为
a = &&a[0][0]
2.3 指针数组和二级指针
找奥运五环色的位置,用二级指针操作指针数组
/* 找奥运五环色的位置,用二级指针操作指针数组 */
#include <stdio.h>
#include <string.h>
int main()
{
int i;
char *color[5] = {"red","blue","yellow","green","black"};
/* 指针数组初始化 */
char ** pc; /* 定义二级指针变量 */
char str[20];
pc = color; /*二级指针赋值 */
printf("Input a color: \n");
scanf("%s",str);
for(i = 0; i < 5; i++){
if(strcmp(str,*(pc+i)) == 0) break;
}
if(i < 5){
printf("position:%d\n",i+1);
}
else{
printf("Not found\n");
}
return 0;
}
3. 用指针数组处理多个字符串
3.1 指针数组和二维数组
char ccolor[][7] = {"red","blue","yellow","green","black"};//二维数组
char *pcolor = {"red","blue","yellow","green","black"};//指针数组
定义二维数组必须制定列长度,该长度要大于最长的字符串的有效长度,由于各个字符串的长度一般并不相同,会造成内存单元的浪费。而指针数组并不存放字符串,仅仅用数组元素指向各个字符串,就没有类似问题。这就是用它的原因吗?
3.2 指针数组操作多个字符串
例1:将5个字符串从小到大排序后输出,用指针数组实现
#include <stdio.h>
#include <string.h>
void fsort(char * color[],int n);
int main()
{
int i;
char *pcolor[] = {"red","blue","yellow","green","black"};
fsort(pcolor,5);
for(i = 0; i < 5; i++){
printf("%s \t",pcolor[i]);
}
return 0;
}
void fsort(char * color[],int n)
{
int k,j;
char *temp;
for(k = 1; k < n; k++){
for(j = 0; j < n-k; j++){
if(strcmp(color[j],color[j+1]) > 0){
temp = color[j];
color[j] = color[j+1];
color[j+1] = temp;
}
}
}
}
例2:解密藏头诗,指针数组操作
#include <stdio.h>
int main()
{
int i;
char *poem[4] = {"一叶轻舟向东流","帆梢轻握杨柳手","风纤碧波微起舞","顺水任从雅客悠"};
char mean[10];
for(i = 0; i < 4; i++){
mean[2*i] = *(poem[i]);
mean[2*i+1] = *(poem[i]+1);
}
mean[2*i] = '\0';
printf("%s",mean);
return 0;
}
3.3 动态输入多个字符串
采用动态分配内存的方法来处理多个字符串的输入问题,是一种较好的解决方案。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int i, n = 0;
char *color[20],str[15];
printf("Please input some words about color: \n");
scanf("%s",str);
while(str[0] != '#'){
color[n] = (char*)malloc(sizeof(char)*(strlen(str)+1));
strcpy(color[n],str);
n++;
scanf("%s",str);
}
printf("These words are:");
for(i = n-1; i >= 0; i--){
printf("%s ",color[i]);
free(color[i]);
}
return 0;
}