英文:
How do I fix 'cannot initialize a variable of type int*' error when using 2D arrays in C++?
问题
我在这段代码中遇到了以下错误:
无法使用类型为'int *'的lvalue来初始化变量'int[3][3]'
#include <iostream>
using namespace std;
int main(){
int mat_1[3][3]={1,2,3,4,5,6,7,8,9};
int mat_2[3][3]={10,11,12,13,14,15,16,17,18};
int dest_mat[3][3];
int *ptr_1 = mat_1;
int *ptr_2 = mat_2;
int *ptr_3 = dest_mat;
我期望只是为以下每个创建一个指针。我甚至尝试在矩阵名称前放置“&”,但结果仍然没有变化。
英文:
I am getting this error for this code:
> Cannot initialize a variable of type 'int *' with an lvalue of type 'int[3][3]'
#include <iostream>
using namespace std;
int main(){
int mat_1[3][3]={1,2,3,4,5,6,7,8,9};
int mat_2[3][3]={10,11,12,13,14,15,16,17,18};
int dest_mat[3][3];
int *ptr_1 = mat_1;
int *ptr_2 =mat_2;
int *ptr_3=dest_mat;
I am expecting to just create a pointer for each of the following. I even tried placing the ampersand (&
) before the matrix names, but still no different.
答案1
得分: 3
在大多数情境下,当你仅使用数组名称引用它时,它会*衰变*为指向其第一个元素的指针。
mat_1
是一个包含3个元素的数组,其中每个元素都是一个包含3个int
的数组。因此,当你执行:
int *ptr_1 = mat_1;
mat_1
衰变为指向其第一个元素的指针,即指向一个int[3]
数组的指针(也称为int(*)[3]
)。数组的指针与单个int
的指针是非常不同的类型,这就是你看到的错误的原因。`
对于
ptr_2和
ptr_3也是一样的。
根据你试图实现的目标,你需要做以下之一:
-
为
ptr_1
(以及ptr_2
和ptr_3
)分配第一个数组元素的第一个int
的地址,例如:int *ptr_1 = &mat_1[0][0];
这可以简化为以下形式(让内部数组衰变):
int *ptr_1 = mat_1[0];
-
将
ptr_1
(以及ptr_2
和ptr_3
)的类型更改为指向int
数组的指针,而不是指向单个int
的指针,例如:int (*ptr_1)[3] = mat_1;
英文:
In most contexts, when you refer to an array by its name alone, it decays into a pointer to its 1st element.
mat_1
is an array of 3 elements, where each element is an array of 3 int
s. So, when you do:
int *ptr_1 = mat_1;
mat_1
decays into a pointer to its 1st element, ie a pointer to an int[3]
array (aka int(*)[3]
). A pointer to an array is a very different type than a pointer to a single int
, thus the error you are seeing.
Same with ptr_2
and ptr_3
.
Depending on what you are attempting to accomplish, you need to either:
-
assign
ptr_1
(andptr_2
andptr_3
) the address of the 1stint
of the 1st array element, eg:int *ptr_1 = &mat_1[0][0];
which can be simplified as follows (letting the inner array decay):
int *ptr_1 = mat_1[0];
-
change the type of
ptr_1
(andptr_2
andptr_3
) to be a pointer to an array ofint
s, not a pointer to a singleint
, eg:int (*ptr_1)[3] = mat_1;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论