int (* p)[3]和int* p[3]的区别?
指针存储变量或内存位置的地址。指针是地址的符号表示。它们使程序能够模拟按引用调用以及创建和操作动态数据结构。在C/C++中,它的一般声明格式为:
语法:
datatype * var_name;
示例:
int *ptr;
在此示例中,“ptr”是指针的变量名称,它保存整数变量的地址。
在本文中,重点区分两种指针声明,即: int (*p) [3] 和 int* p [3]。
对于int (*p) [3]: 这里“p”是指针的变量名称,可以指向三个整型数组。
下面的示例说明了如何使用int (*p) [3]:
// C++ program to illustrate the use
// of int (*p)[3]
#include <iostream>
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;
}
1 2 3
对于int* p [3]: 这里“p”是一个大小为3的数组,可以存储整数指针。
下面的示例说明了如何使用int* p [3]:
// C++ program to illustrate the use
// of int*p[3]
#include <bits/stdc++.h>
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