【问题标题】:How to fix Value of type cannot be assigned to entity of type ERROR?如何修复类型的值不能分配给错误类型的实体?
【发布时间】:2022-01-16 07:08:20
【问题描述】:

我正在使用用户输入的行和列在 c++ 中开发一个二维数组,并希望为列分配内存,但我不断收到错误消息;

“int”类型的值不能分配给“int”类型的实体

我知道错误的含义,但是我该如何解决它这很烦人。 下面是我的部分代码。我也没有包括打印部分,因为我希望以后能够转置数组。

    // Local variables
    int rows, columns;

    // Prompting the user to enter the number of rows and columns
    std::cout << "please input how many rows and columns you want accordingly: " << std::endl;
    std::cin >> rows >> columns;

    // Creating an array on the Heap memory and sizing it by the number of rows
    int* arr = new int[rows]; 

    // Assigning the values of rows
    for (int i = 0; i < rows; i++) { 

        // Creating a new heap for columns into arr[i]
        arr[i] = new int[columns];
    }

    // Getting the values of rows
    for (int i = 0; i < rows; i++) {
        // Assigning and Getting the values of columns
        for (int j = 0; j < columns; j++) {

            // Enter the elements of the array
            std::cout << "Please enter a number: " << std::endl;
            std::cin >> arr[i][&j];
        }
    }

【问题讨论】:

  • std::cin &gt;&gt; arr[i][&amp;j] 你正在使用i 的地址,你应该使用i 本身。
  • 为什么是C标签?潜入更多流量?我认为它是垃圾邮件。已移除

标签: c++ debugging visual-c++ computer-science


【解决方案1】:

在这一行:

arr[i] = new int[columns];

您正在尝试将 int * 值分配给 int

您需要将arr 定义为int *,并将第一个new 更改为new int *[]

int **arr = new int *[rows]; 

另外,这是不正确的:

std::cin >> arr[i][&j];

当您使用地址作为数组索引时。你想要:

std::cin >> arr[i][j];

【讨论】:

  • 好吧,有道理。感谢您的帮助,但为什么 int **arr 处的双指针?
  • @essiendreamer28 你首先创建了一个int * 的数组,然后每个指针都可以指向一个int 的数组。
【解决方案2】:
#include <iostream>
using namespace std;

int main(int argc, char** argv) {
    
    int row,col;
    cout << "please input how many rows and columns you want accordingly: ";
    cin>>row>>col;
    //create array in heap.
    int **arr=new int*[row];
    for(int i=0;i<row;i++)
    {
        arr[i]=new int[col];
    }
    //getting value from user.
    for(int i=0;i<row;i++)
    {
        for(int j=0;j<col;j++)
        {
            cout<<"Enter a number ";
            cin>>arr[i][j];
        }
    }
    //display Elements.
        for(int i=0;i<row;i++)
    {
        for(int j=0;j<col;j++)
        {
            cout<<arr[i][j]<<" ";
        }
    }
    
    return 0;
}

【讨论】:

    猜你喜欢
    • 2018-02-17
    • 1970-01-01
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    • 2014-03-23
    • 1970-01-01
    相关资源
    最近更新 更多