我正在使用用戶輸入的行和列在 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];
}
}
uj5u.com熱心網友回復:
在這一行:
arr[i] = new int[columns];
您正在嘗試的分配int *值的int。
您需要定義arr為 anint *并將第一個更改new為new int *[]:
int **arr = new int *[rows];
此外,這是不正確的:
std::cin >> arr[i][&j];
當您使用地址作為陣列索引時。你要:
std::cin >> arr[i][j];
uj5u.com熱心網友回復:
#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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/379806.html
