Home > Backend Development > C++ > body text

C program to print array of pointers to strings and their addresses

PHPz
Release: 2023-08-26 21:01:01
forward
1039 people have browsed it

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

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

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

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

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

在这里,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 : </p><p>");
   for(i=0;i<5;i++){
      printf("%s</p><p>",a[i]);
   }
   //Printing addresses within each string location using for loop//
   printf("The address locations of every string values are : </p><p>");
   for(i=0;i<5;i++){
      printf("%d</p><p>",a[i]);
   }
}
Copy after login

输出

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

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
Copy after login

示例 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!=&#39;\0&#39;){
      printf("%s",*pointer);
      pointer++;
   }
}
Copy after login

输出

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

The string is: TutorialPoint
Copy after login

The above is the detailed content of C program to print array of pointers to strings and their addresses. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!