如何在C / C ++中使用指针数组(锯齿状)?
让我们请看以下示例,该示例使用3个整数组成的数组-
在C中
示例
#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] = 10Value of var[1] = 100
Value of var[2] = 200
在C ++中
示例
#include <iostream>using namespace std;
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i;
for (i = 0; i < MAX; i++) {
cout<<"Value of var"<<i<<"="<<var[i]<<"\n";
}
return 0;
}
输出结果
Value of var0=10Value of var1=100
Value of var2=200
在某些情况下,我们想要维护一个数组,该数组可以存储指向int或char或任何其他可用数据类型的指针。以下是指向整数的指针数组的声明-
int * ptr [MAX]
它将ptr声明为MAX个整数指针的数组。因此,ptr中的每个元素都持有一个指向int值的指针。以下示例使用三个整数,它们存储在指针数组中,如下所示:
在C中
示例
#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]; /* assign the address of integer. */
}
for ( i = 0; i < MAX; i++) {
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0;
}
输出结果
Value of var[0] = 10Value of var[1] = 100
Value of var[2] = 200
在C ++中
示例
#include <iostream>using namespace std;
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]; /* assign the address of integer. */
}
for ( i = 0; i < MAX; i++) {
cout<<"Value of var" << i<<"="<<*ptr[i] <<"\n";
}
}
输出结果
Value of var0=10Value of var1=100
Value of var2=200
您还可以使用指向字符的指针数组来存储字符串列表,如下所示:
在C中
示例
#include <stdio.h>const int MAX = 4;
int main () {
char *names[] = {
"Zara Ali",
"Hina Ali",
"Nuha Ali",
"Sara Ali"
};
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] = Zara AliValue of names[1] = Hina Ali
Value of names[2] = Nuha Ali
Value of names[3] = Sara Ali
在C ++中
示例
#include <iostream>using namespace std;
const int MAX=4;
int main () {
char *names[] = {
"Zara Ali",
"Hina Ali",
"Nuha Ali",
"Sara Ali"
};
int i = 0;
for ( i = 0; i < MAX; i++) {
cout<<"Value of names"<< i<<"="<< names[i]<<"\n";
}
return 0;
}
输出结果
Value of names0=Zara AliValue of names1=Hina Ali
Value of names2=Nuha Ali
Value of names3=Sara Ali
以上是 如何在C / C ++中使用指针数组(锯齿状)? 的全部内容, 来源链接: utcz.com/z/341124.html