如何使用 C 语言创建指向字符串的指针?
cserver side programmingprogramming更新于 2025/5/15 12:22:17
指针数组(指向字符串)
指针数组是一个数组,其元素是指向字符串基地址的指针。
它的声明和初始化如下 −
char *a[3 ] = {"one", "two", "three"}; //这里,a[0] 是指向字符串 "one" 基地址的指针 //a[1] 是指向字符串 "two" 基地址的指针 //a[2] 是指向字符串 "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]); //打印字符串数组 getch (); }
输出
The strings are: one two three four five
示例 2
考虑另一个字符串指针数组示例 −
#include <stdio.h> #include <String.h> int main(){ //初始化指针字符串数组 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