从兼容类型int中赋值给int
Assigning to int from Compatible type int
在粗体部分,我遇到了编译错误。有人帮忙找出错误吗?我的代码如下。。。
void _multiDimensionalArray(){
int row = 10;
int column = 10;
cout << "nn For a 2-Dimensional Array:>>>>" << endl;
// 2D array is basically an array of pointers to arrays
// dynamic array of size 100
int pDoubleArray = new int*[row];
for (int i=0; i<column; i++) {
pDoubleArray[i] = new int[column];
}
// e) exchange rows: 0<------>9 and 3<------>4
int (*ptemp)[10][1]; // temp is a pointer to an array of 10 ints
ptemp = pDoubleArray;
for (int i=0; i<10; i++) {
ptemp[i][0] = *(ptemp+4);
}
for (int i=0; i<10; i++) {
cout << ptemp[i] << " " ;
}
} // end of _multiDimensionalArray function
这些对象具有不同类型的
int **pDoubleArray;
int (*ptemp)[10][1];
因此,您可能不会使用分配
ptemp = pDoubleArray;
即使使用强制转换,代码也将无效。
考虑到该分配也是无效的
int pDoubleArray = new int*[row];
for (int i=0; i<column; i++) {
pDoubleArray[i] = new int[column];
必须使用行而不是条件中的列
for (int i=0; i<row; i++) {
请考虑您没有初始化已分配的数组。
如果你需要像你在评论中所说的那样交换一些东西,那么就把每个元素互相交换。我认为创建指向数组的指针没有任何意义。
例如,如果你想交换第1行和第9行,那么你可以简单地写
int *tmp = pDoubleArray[1];
pDoubleArray[1] = pDoubleArray[9];
pDoubleArray[9] = tmp;
这是一个演示程序
#include <iostream>
int main()
{
int row = 10;
int column = 10;
int **p = new int *[row];
for ( int i = 0; i < row; i++ ) p[i] = new int[column];
for ( int i = 0; i < column; i++ ) p[1][i] = i;
for ( int i = 0; i < column; i++ ) p[9][column - i - 1] = i;
for ( int i = 0; i < column; i++ ) std::cout << p[1][i] << ' ';
std::cout << std::endl;
for ( int i = 0; i < column; i++ ) std::cout << p[9][i] << ' ';
std::cout << std::endl;
int *tmp = p[1];
p[1] = p[9];
p[9] = tmp;
for ( int i = 0; i < column; i++ ) std::cout << p[1][i] << ' ';
std::cout << std::endl;
for ( int i = 0; i < column; i++ ) std::cout << p[9][i] << ' ';
std::cout << std::endl;
for ( int i = 0; i < row; i++ ) delete [] p[i];
delete []p;
return 0;
}
输出为
0 1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1 0
9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9
正如你所看到的,两排被调换了。
您只需要引用指针的第一个值。一旦引用了第一个指针,根据数据类型每隔一个字的长度,就会进行引用。
相关文章:
- cin >> int 给定一个字符串将 int 赋值为 0
- 数组类型 int[n][n] 不可赋值,因为表达式必须具有常量值
- 赋值和添加运算符重载(2个表和int的串联)
- 程序无法编译:将 'int (*)[3][3]' 赋值为 'int [9][3][3]' 中的不兼容类型
- 如何修复数组赋值从 ascii 值到 int
- 为什么SDL_QueryTexture不为其 int* 参数赋值?
- 不能为类中的 int 赋值
- 在没有初始化列表的情况下,在c++的headerfile中为const int赋值
- 错误:在 GEANY 中将"int"赋值为"char [1]"时类型不兼容
- 将int***赋值给int[][][]
- C++ int 赋值不起作用
- 如何将int赋值给具有字符串流的字符串
- 当我在C++中将临时int赋值给const引用时会发生什么
- 错误:将"int"赋值为"int[2]"时的类型不兼容
- 将const int赋值给指向int的const指针是非法的
- "无符号长整型"和'unsigned long long int'赋值问题
- 将int[][]赋值给int**
- 如果允许将int赋值给float(反之亦然),是否不类型安全?
- 不能将int赋值给返回类的int成员
- 在while循环中滥用cin进行int赋值