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

PHPz
PHPz 转载
2023-08-26 21:01:01 373浏览

首先,让我们了解一下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!='\0'){
      printf("%s",*pointer);
      pointer++;
   }
}

输出

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

The string is: TutorialPoint

以上就是C 程序打印指向字符串的指针数组及其地址的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除