卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章16333本站已运行3317

C 程序打印指向字符串的指针数组及其地址

首先,让我们了解一下C编程语言中的指针数组。

指针数组:(指向字符串)

  • 它是一个数组,其元素是指向字符串基地址的指针。

  • 它的声明和初始化如下所示:

char *a[ ] = {"one", "two", "three"};

在这里,a[0]是指向字符串"one"的基地址的指针。

a[1]是指向字符串"two"的基地址的指针。

a[2]是指向字符串"three"的基地址的指针。

C 程序打印指向字符串的指针数组及其地址

优点

指针数组的优点如下所述 −

  • 与二维字符数组不同,在字符串数组和指向字符串的指针数组中,没有固定的存储内存大小。

  • 字符串只占用所需的字节数,因此不会浪费空间。

示例

下面给出了演示打印指向字符串的指针数组和地址的C程序示例 −

#include<stdio.h>
#include<string.h>
void main(){
   //Declaring string and pointers, for loop variable//
   int i;
   char *a[5]={"One","Two","Three","Four","Five"};
   //Printing values within each string location using for loop//
   printf("The values in every string location are : 

"); for(i=0;i<5;i++){ printf("%s

",a[i]); } //Printing addresses within each string location using for loop// printf("The address locations of every string values are :

"); for(i=0;i<5;i++){ printf("%d

",a[i]); } }

输出

当执行上述程序时,会产生以下结果 -

The values in every string location are:
One
Two
Three
Four
Five
The address locations of every string values are:
4210688
4210692
4210696
4210702
4210707

示例 2

让我们考虑另一个示例。

下面是一个 C 程序,演示了指向字符串的指针数组的概念 -

#include<stdio.h>
#include<string.h>
void main(){
   //Declaring string and pointers//
   char string[10]="TutorialPoint";
   char *pointer = string;
   //Printing the string using pointer//
   printf("The string is : ");
   while(*pointer!=''){
      printf("%s",*pointer);
      pointer++;
   }
}

输出

当执行上述程序时,会产生以下结果 -

The string is: TutorialPoint

卓越飞翔博客
上一篇: 基于PHP的实时聊天系统的用户头像和个性装扮设置
下一篇: 如何实现C++中的模板和泛型编程特性?
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏