C++ 如何使用指针而不是数组访问元素

C++ 如何使用指针而不是数组访问元素,c++,arrays,pointers,C++,Arrays,Pointers,我有一段代码,目前正在运行(至少): 然后我收到这个错误: argument of type "int" is incompatible with parameter of type "int *" 首先,我从数组到指针的转换编码正确吗?如果它是正确的,我如何初始化它以避免上述错误?我认为您将常数5和3作为参数传递,从而导致此错误。 无法按引用的方式传递常量值。请尝试通过将它们存储在变量中来传递5和3。首先,很明显,函数中的此语句 arr[i] = &totalCol [0]; 这是

我有一段代码,目前正在运行(至少):

然后我收到这个错误:

argument of type "int" is incompatible with parameter of type "int *"

首先,我从数组到指针的转换编码正确吗?如果它是正确的,我如何初始化它以避免上述错误?

我认为您将常数5和3作为参数传递,从而导致此错误。
无法按引用的方式传递常量值。请尝试通过将它们存储在变量中来传递5和3。

首先,很明显,函数中的此语句

arr[i] = &totalCol [0];
这是错误的。这没有道理

您声明了函数

int** constructSparseMatrix(int *totalRow, int *totalCol, int totalEl);
将第一个和第二个参数作为指针,但试图在调用中向其传递整数文本5和3

int** arr = constructSparseMatrix(5,3,totalEl);
你可以写一个例子

int totalRow = 5;
int totalCol = 3;
//

但是我不认为像指针一样声明这些参数是有意义的,因为它们实际上是函数中的常量,因此它们不会被更改

变量名会让读者感到困惑。例如,我希望在语句中的函数中使用
totalRow

int** arr = new int*[totalRow];
而不是
totalEl

如果希望在函数中使用指针,那么函数可以如下所示

int** constructSparseMatrix( int totalRow, int totalCol, int totalEl ) 
{
    int** arr = new int*[totalEl];

    for ( int **p = arr; p < arr + totalEl; ++p ) 
    {
        *p = new int[totalCol];
        for ( int *q = *p; q < *p + totalCol; ++q ) 
        {
            if ( q == *p + totalCol - 1 ) 
            {
                *q = rand () % 101;
            } 
            else 
            {
                *q = rand () % totalRow + 1;
            }
        }
    }

    return arr;
}
int**ConstructionSparseMatrix(intTotalRow、intTotalCol、intTotalEl)
{
int**arr=新int*[totalEl];
对于(int**p=arr;p
您一直在说指针而不是数组,但我认为它的含义与您认为的不同。您从未使用数组,而是使用一个值,该值可能表示一列和一行中有多少个元素。然后用指针替换该值。你想做什么?你更改的目的是什么?因此我不需要对我的初始版本进行任何更改,因为它已经正确了?@Pewds如果totalRow和totalEl的用法正确,那么函数就正确了。嗨,弗拉德,我有一个错误:
类型为“int**”的值不能用于初始化类型为“int*的实体”
at
int*q=p
。你的代码有问题吗?
int totalRow = 5;
int totalCol = 3;
int** arr = constructSparseMatrix( &totalRow, &totalCol, totalEl );
int** arr = new int*[totalRow];
int** constructSparseMatrix( int totalRow, int totalCol, int totalEl ) 
{
    int** arr = new int*[totalEl];

    for ( int **p = arr; p < arr + totalEl; ++p ) 
    {
        *p = new int[totalCol];
        for ( int *q = *p; q < *p + totalCol; ++q ) 
        {
            if ( q == *p + totalCol - 1 ) 
            {
                *q = rand () % 101;
            } 
            else 
            {
                *q = rand () % totalRow + 1;
            }
        }
    }

    return arr;
}