使用指针演示字符串概念的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
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP