我正在从用户那里获取数组大小的输入,然后是它的元素。
在下面的代码中,第一个for
循环中的cin>>A[i]
给了我一个错误。
从与此类似的其他问题来看,这是一个简单的运算符错误,并且脚本类似于我见过的三维脚本。默认情况下new
创建三维数组,这意味着我也需要定义列吗?如果没有,我会在哪里错过操作员?
int** A;
int s;
cin >> s;
A = new int*[s];
for(int i=0;i<s;i++)
{
A[i]=new int[s];
cout<< "Enter value: ";
cin>>A[i];
}
cout<< "Array:n";
for(int j=0;j<s;j++)
{
cout << A[j] << " ";
}
A[]
是一个int*
指针,而不是一个int
值。
没有operator>>
可以将int
值读入int*
指针。 由于要读取int
值,因此必须读取int
变量,因此请将第一个循环中的A[i]
更改为*A[i]
:
cin >> *A[i];
您需要对第二个循环中的A[j]
执行相同的操作:
cout << *A[j] << " ";
这是因为没有从int*
指针写入int
值的operator<<
,但有一个operator<<
可以写入void*
指针持有的内存地址的值,并且int*
可以隐式转换为void*
。
使用完数组后
,不要忘记delete[]
数组:int s;
cin >> s;
int** A = new int*[s];
for(int i = 0; i < s; ++i)
A[i] = new int[s];
for(int i = 0; i < s; ++i)
{
cout << "Enter value: ";
cin >> *A[i];
}
cout << "Array:n";
for(int j = 0; j < s; ++j)
cout << *A[j] << " ";
for(int j = 0; j < s; ++j)
delete[] A[j];
delete[] A;
话虽如此,您在s > 1
时浪费了第二维的内存,因为您只填写并使用第一列而忽略了其他列。 您显示的代码实际上只需要一个一维数组:
int s;
cin >> s;
int* A = new int[s];
for(int i = 0; i < s; ++i)
{
cout << "Enter value: ";
cin >> A[i];
}
cout << "Array:n";
for(int j = 0; j < s; ++j)
cout << A[j] << " ";
delete[] A;
如果你真的想要一个二维数组,请尝试更像这样的东西:
int rows, columns;
cin >> rows;
cin >> columns;
int** A = new int*[rows];
for(int i = 0; i < rows; ++i)
A[i] = new int[columns];
for(int i = 0; i < rows; ++i)
{
for(int j = 0; j < columns; ++j)
{
cout << "Enter value for (" << i << "," << j << "): ";
cin >> A[i][j];
}
}
cout << "Array:n";
for(int i = 0; i < rows; ++i)
{
for(int j = 0; j < columns; ++j)
cout << A[i][j] << " ";
cout << endl;
}
for(int i = 0; i < rows; ++i)
delete A[i];
delete[] A;
话虽如此,您确实应该使用std::vector
而不是直接使用new[]
。
您要创建什么数组?二维 SxS,还是只是 S 大小? 因为您正在创建一个数组数组,同时尝试将其作为一维访问。
将int** A
更改为int* A
,A = new int*[s]
更改为A = new int[s]
,并在第一个循环中去除A[i]=new int[s]
使代码正确。