Home > Net >  How to fix Value of type cannot be assigned to entity of type ERROR?
How to fix Value of type cannot be assigned to entity of type ERROR?

Time:12-13

I am developing a 2-Dimensional array in c using user input of rows and columns and want to allocate memory for the columns but I keep receiving an error which states;

A value of type "int" cannot be assigned to entity of type "int"

I know what the error means but how do I fix it it is annoying. Below is a portion of my code. Also I did not include the print section as I want to be able to transpose the array later.

    // 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];
        }
    }

CodePudding user response:

On this line:

arr[i] = new int[columns];

You're attempting to assign an int * value to an int.

You need to define arr as an int * and change the first new to new int *[]:

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

Also, this is not correct:

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

As you're using an address as an array index. You want:

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

CodePudding user response:

#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;
}
  • Related