使用指標演示字串概念的C程式


字元陣列稱為字串。

宣告

宣告陣列的語法如下:

char stringname [size];

例如:char string[50]; 長度為50個字元的字串

初始化

  • 使用單字元常量:
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
  • 使用字串常量:
char string[10] = "Hello":;

訪問 - 使用控制字串“%s”訪問字串,直到遇到‘\0’。

現在,讓我們瞭解一下C程式語言中的指標陣列。

指標陣列:(指向字串)

  • 它是一個數組,其元素是指向字串基地址的指標。
  • 宣告和初始化如下:
char *a[ ] = {"one", "two", "three"};

這裡,a[0]是指向字串“one”基地址的指標。

    a[1]是指向字串“two”基地址的指標。

    a[2]是指向字串“three”基地址的指標。

示例

下面是一個演示字串概念的C程式:

 線上演示

#include<stdio.h>
#include<string.h>
void main(){
   //Declaring string and pointers//
   char *s="Meghana";
   //Printing required O/p//
   printf("%s
",s);//Meghana//    printf("%c
",s);//If you take %c, we should have * for string. Else you    will see no output////    printf("%c
",*s);//M because it's the character in the base address//    printf("%c
",*(s+4));//Fifth letter a because it's the character in the (base address+4)th position//    printf("%c
",*s+5);//R because it will consider character in the base address + 5 in alphabetical order// }

輸出

執行上述程式時,會產生以下結果:

Meghana
M
a
R

示例2

考慮另一個例子。

下面是一個演示使用後增量和前增量運算子列印字元概念的C程式:

 線上演示

#include<stdio.h>
#include<string.h>
void main(){
   //Declaring string and pointers//
   char *s="Meghana";
   //Printing required O/p//
   printf("%s
",s);//Meghana//    printf("%c
",++s+3);//s becomes 2nd position - 'e'. O/p is Garbage value//    printf("%c
",s+++3);//s becomes 3rd position - 'g'. O/p is Garbage value//    printf("%c
",*++s+3);//s=3 becomes incremented by 1 = 'h'.s becomes 4th    position.h+3 - k is the O/p//    printf("%c
",*s+++3);//s=4 - h is the value. h=3 = k will be the O/p. S is incremented by 1 now. s=5th position// }

輸出

執行上述程式時,會產生以下結果:

Meghana
d
d
k
k

更新於:2021年3月19日

2K+ 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.