如何使用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:\n");
for(i=0 ;i<4 ;i++ )
printf("%s\n",students[i]);
return 0;
}
The names of students are:bhanu
ramu
hari
pinky
以上是 如何使用C语言为字符串创建指针? 的全部内容, 来源链接: utcz.com/z/341418.html