[英]What is this pointer type and how to use it?
okay so i have come across this pointer type and i tried to use it in my code but i get a warning from the compiler saying its in incompatible pointer type 好吧,所以我遇到了这个指针类型,我试图在我的代码中使用它,但是我从编译器收到警告,说它的指针类型不兼容
this is the type 这是类型
data_type (*i)[j]
with i
being the variable name and j
being the size of the pointer data_type (*i)[j]
其中i
是变量名, j
是指针的大小
for example if you want the pointer to be as size of 4 ints you would declare 例如,如果您希望指针的大小为4 int,则可以声明
int (*i)[4]
and then you would need to assign an array of 4 ints int (*i)[4]
,然后您需要分配4个int数组
i = &s[4]
however when i try to assign it, i get a warning from compiler saying incompatible type
但是,当我尝试分配它时,我从编译器收到警告,指出
incompatible type
so what seems to be the problem here? 那么这里似乎是什么问题呢? and how do i use it correctly?
以及我如何正确使用它?
int (*i)[4];
declares i
to be a pointer to an array of 4
int
s. 声明
i
为指向4
int
数组的指针。 You said s
is an array of 4
int
您说
s
是4
int
的数组
int s[4];
assignment 分配
i = &s[4];
is wrong because &s[4]
is the address of memory block just past the array and is of type int *
. 这是错误的,因为
&s[4]
是刚刚超过数组的内存块的地址,并且是int *
类型的。 Generally arrays decay into pointer to its first element but in case of as an operand of unary &
operator it doesn't decay and therefore &s
gives the address of array s
which is of type int (*)[4]
. 通常,数组会衰减为指向其第一个元素的指针,但在作为一元
&
运算符的操作数的情况下,它不会衰减,因此&s
给出的数组s
的地址为int (*)[4]
。
i = &s;
If j
is variable, then I'd recommend to use std::vector
instead and take a reference to the container rather than a pointer: 如果
j
是变量,那么我建议改用std::vector
并引用容器而不是指针:
std::vector<int> i(j);
auto& i_ref = i;
If j
is a constant expression, I'd still avoid using C-style arrays and use std::array
instead, and still take only a reference: 如果
j
是一个常量表达式,我仍将避免使用C样式数组,而应使用std::array
,并且仍然仅使用引用:
constexpr std::size_t j = 4;
std::array<int, j> i;
auto& i_ref = i;
This 这个
int s[4];
declares s
to be array of 4
int
s. 声明
s
为4
int
数组。
Using the expression s[4]
(after s
had been defined) would evaluated to the 5th element of s
(an int
). 使用表达式
s[4]
(已定义s
之后)将求值到s
的第五个元素(一个int
)。
As s
only has 4
elements, doing so is "illegal" and provokes undefined behaviour of the program. 由于
s
只有4
元素,所以这样做是“非法的”,并且会引起程序的未定义行为。
So to assign to int(*i)[4]
the address of s
do: 因此,将
s
的地址分配给int(*i)[4]
:
i = &s;
If using C99 or later to initialise i
without declaring s
you might also do: 如果使用C99或更高版本来初始化
i
而不声明s
那么您也可以这样做:
i = &(int[4]){0};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.