使用指针数组,实现输出数组中的指定字符串
一、指针数组是什么?
指针数组是一个数组,其中的每个元素都是指针。这意味着每个元素存储的是一个地址,该地址指向内存中的某个位置。
二、使用步骤
1.常见的操作方式
代码如下(示例):
#include <stdio.h>
int main()
{
int a[3] = {10,20,30};
int *p[3] = {&a[0],&a[1],&a[2]};//将对应的数组元素的地址指向对应的指针
for(int i = 0;i < 3;i++)
{
printf("%d ",*p[i]);通过循环输出指针指向的地址中的元素
}
return 0;
}
2.读入数据
两种输出方式:
printf("The month is:%s\n",month[n-1]);
printf("The month is:%s\n",*(month + n -1));
三、程序示例
1.程序要求
使用指针数组创建一个含有月份英文名的字符串数组,并使用指向指针的指针指向这个字符串数组,实现输出数组中的制定字符串。
2.程序如下
//输入月份号并输入英文月份名
#include <stdio.h>
int main()
{
char *month[] = {"January","February","March","April","May","June","July","August","September","October","November","December"};
int n = 0;
printf("Input a number for month\n");
scanf("%d",&n);
printf("====================\n");
printf("The month is:%s\n",month[n-1]);
printf("====================\n");
printf("The month is:%s\n",*(month + n -1));
return 0;
}
3.运行效果
Input a number for month
7
====================
The month is:July
====================
The month is:July