指针存储变量的地址或内存位置。指针是地址的符号表示。它们使程序能够模拟按引用调用以及创建和操作动态数据结构。它在 C/C++ 中的一般声明格式为:
句法:
datatype *var_name;
例子:
int *ptr;In this example “ptr” is a variable name of the pointer that holds address of an integer variable.
在本文中,重点是区分指针的两种声明,即int (*p)[3]和int *p[3]。
对于int (*p)[3]:这里的“p”是指针的变量名,它可以指向一个由三个整数组成的数组。
下面是一个示例来说明int (*p)[3]的用法:
C++
// C++ program to illustrate the use
// of int (*p)[3]
#include
using namespace std;
// Driver Code
int main()
{
// Declaring a pointer to store address
// pointing to an array of size 3
int(*p)[3];
// Define an array of size 3
int a[3] = { 1, 2, 3 };
// Store the base address of the
// array in the pointer variable
p = &a;
// Print the results
for (int i = 0; i < 3; i++) {
cout << *(*(p) + i) << " ";
}
return 0;
}
C++
// C++ program to illustrate the use
// of int*p[3]
#include
using namespace std;
// Driver Code
int main()
{
// Declare an array of size 3 which
// will store integer pointers
int* p[3];
// Integer variables
int a = 1, b = 2, c = 3;
// Store the address of integer
// variable at each index
p[0] = &a;
p[1] = &b;
p[2] = &c;
// Print the result
for (int i = 0; i < 3; i++) {
cout << *p[i] << " ";
}
return 0;
}
输出:
1 2 3
对于int *p[3]:这里的“p”是 一个大小为 3 的数组,可以存储整数指针。
下面是一个示例来说明int *p[3]的用法:
C++
// C++ program to illustrate the use
// of int*p[3]
#include
using namespace std;
// Driver Code
int main()
{
// Declare an array of size 3 which
// will store integer pointers
int* p[3];
// Integer variables
int a = 1, b = 2, c = 3;
// Store the address of integer
// variable at each index
p[0] = &a;
p[1] = &b;
p[2] = &c;
// Print the result
for (int i = 0; i < 3; i++) {
cout << *p[i] << " ";
}
return 0;
}
输出:
1 2 3
想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解基础加 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程。