从兼容类型int中赋值给int

Assigning to int from Compatible type int

本文关键字:int 赋值 类型      更新时间:2023-10-16

在粗体部分,我遇到了编译错误。有人帮忙找出错误吗?我的代码如下。。。

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 

正如你所看到的,两排被调换了。

您只需要引用指针的第一个值。一旦引用了第一个指针,根据数据类型每隔一个字的长度,就会进行引用。