如何在使用C++中的二维数组时修复“无法初始化int*类型变量”的错误?

huangapple go评论55阅读模式
英文:

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 &lt;iostream&gt;
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 (&amp;) 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_2ptr_3也是一样的。

根据你试图实现的目标,你需要做以下之一:

  • ptr_1(以及ptr_2ptr_3)分配第一个数组元素的第一个int的地址,例如:

    int *ptr_1 = &mat_1[0][0];

    这可以简化为以下形式(让内部数组衰变):

    int *ptr_1 = mat_1[0];

  • ptr_1(以及ptr_2ptr_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 ints. 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 (and ptr_2 and ptr_3) the address of the 1st int of the 1st array element, eg:

    int *ptr_1 = &amp;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 (and ptr_2 and ptr_3) to be a pointer to an array of ints, not a pointer to a single int, eg:

    int (*ptr_1)[3] = mat_1;

huangapple
  • 本文由 发表于 2023年6月1日 01:26:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76375973.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定