如何使用 C 語言建立指向字串的指標?


指向(字串)的指標的陣列

指標陣列是一個數組,其元素是指向字串的基地址的指標。

它宣告並初始化如下 -

char *a[3 ] = {"one", "two", "three"};
//Here, a[0] is a ptr to the base add of the string "one"
//a[1] is a ptr to the base add of the string "two"
//a[2] is a ptr to the base add of the string "three"

優勢

  • 取消連結二維字元陣列。在(字串陣列)中,在指向字串的指標陣列中,沒有固定的記憶體大小用於儲存。

  • 字串佔用所需的位元組數,因此不會浪費空間。

示例 1

#include<stdio.h>
main (){
   char *a[5] = {“one”, “two”, “three”, “four”, “five”};//declaring array of pointers to
   string at compile time
   int i;
   printf ( “The strings are:”)
   for (i=0; i<5; i++)
      printf (“%s”, a[i]); //printing array of strings
   getch ();
}

輸出

The strings are: one two three four five

示例 2

考慮另一個有關指向字串的指標陣列的示例 -

#include <stdio.h>
#include <String.h>
int main(){
   //initializing the pointer string array
   char *students[]={"bhanu","ramu","hari","pinky",};
   int i,j,a;
   printf("The names of students are:
");    for(i=0 ;i<4 ;i++ )       printf("%s
",students[i]);    return 0; }

輸出

The names of students are:
bhanu
ramu
hari
pinky

更新於:09-Mar-2021

1 千+檢視次數

啟動你的 職業生涯

完成課程獲取認證

開始
廣告
© . All rights reserved.