无涯教程-C语言 - 指针数组函数

57 阅读1分钟

在我们理解指针数组的概念之前,让我们考虑一下下面的示例,该示例使用3个整数的数组

#include <stdio.h>

const int MAX=3;

int main () {

int var[]={10, 100, 200}; int i;

for (i=0; i < MAX; i++) { printf("Value of var[%d]=%d\n", i, var[i] ); }

return 0; }

编译并执行上述代码时,将生成以下结果-

Value of var[0]=10
Value of var[1]=100
Value of var[2]=200

可能会有一种情况,我们想要维护一个数组,它可以存储指向int或char或任何其他可用的数据类型的指针,下面是指向整数的指针数组的声明

int *ptr[MAX];

它将ptr声明为最大整数指针数组,因此,PTR中的每个元素都持有一个指向int值的指针,下面的示例使用三个整数,它们存储在指针数组中,如下所示

#include <stdio.h>

const int MAX=3;

int main () {

int var[]={10, 100, 200}; int i, *ptr[MAX];

for ( i=0; i < MAX; i++) { ptr[i]=&var[i]; /* 分配整数地址。 */ }

for ( i=0; i < MAX; i++) { printf("Value of var[%d]=%d\n", i, *ptr[i] ); }

return 0; }

编译并执行上述代码时,将生成以下结果-

Value of var[0]=10
Value of var[1]=100
Value of var[2]=200

还可以使用指向字符的指针数组来存储字符串列表,如下所示-

#include <stdio.h>

const int MAX=4;

int main () {

char *names[]={ "Learnfk.com", "Toolfk.com", "Poemfk.com", "Chromefk.com" };

int i=0;

for ( i=0; i < MAX; i++) { printf("Value of names[%d]=%s\n", i, names[i] ); }

return 0; }

编译并执行上述代码时,将生成以下结果-

Value of names[0] = Learnfk.com
Value of names[1] = Toolfk.com
Value of names[2] = Poemfk.com
Value of names[3] = Chromefk.com

参考链接

www.learnfk.com/c-programmi…