将2d数组指针传递给C ++中的函数

时间:2018-06-29 04:32:12

标签: c++ arrays function pointers

我知道如何通过以下代码将一维数组指针传递给函数

void fiddleWithArray(int*);   

int main(){

int list[10] = {1, 3, 5, 7, 9, 11, 13, 17};
cout << "List at 0 before being passed is... " << list[0][0] << endl;    
cout << "List at 1 before being passed is... " << list[1][0] << endl;    
fiddleWithArray(list);
cout << "List at 0 after being passed is... " << list[0][0] << endl;    
cout << "List at 1 after being passed is... " << list[1][0] << endl;    

}

void fiddleWithArray(int* input){
input[0] = 45;
input[1] = 18;
}

但是,当我尝试对2D数组执行类似操作(如下所示)时,会出现错误。

void fiddleWithArray (int** input);

int main ()
{
int list [10][2]={{1,3},{5,7},{9,11},{13,17},{7,4},{5,90},{9,1},{3,25}};
int ** pointer;
pointer=&list;
cout<< "List at 0 before being passed is ... "<< list[0][0]<< endl;
cout<< "List at 1 before being passed is ... "<< list[1][0]<< endl;
fiddleWithArray(pointer);
cout<< "List at 0 after being passed is ... "<< list[0][0]<< endl;
cout<< "List at 1 after being passed is ... "<< list[1][0]<< endl;
}

void fiddleWithArray(int** input)
{   
cout << input [6][1]<< endl;
}

编译器给出一个错误,指出“错误:赋值时无法将“ int(*)[10] [2]”转换为“ int **”      指针=&list;“ 我也乐于将2D数组指针传递给函数的替代方法。

2 个答案:

答案 0 :(得分:2)

保留数据结构,如果要将list传递给fiddleWithArray,则可以将其声明为

void fiddleWithArray (int input[][2]);

,然后在主程序中将其命名为

fiddleWithArray(list);

程序中还有另一个问题:cout << list[0]不起作用。如果要在第一个索引固定为0时打印数组的内容,则应编写类似

的内容
cout << list[0][0] << " " << list[0][1]

如果您打算写一个将 second 索引固定为0或1的数组,那么为了使事情变得容易,您需要像这样的短循环

for (unsigned int i = 0; i < 10; i++)
   cout << list[i][0] << " ";
cout << endl;

最后,您可能不想使用C ++ 11中引入的std::array。而不是使用int[][]

答案 1 :(得分:0)

void fiddleWithArray(int input[10][2])
{
    cout << input[6][1] << endl;
}

int main()
{
    int list[10][2] = {{1,3},{5,7},{9,11},{13,17},{7,4},{5,90},{9,1},{3,25}};
    int (*pointer)[10][2];
    pointer=&list;
    cout << "List at 0 before being passed is ... "<< list[0][0]<< endl;
    cout << "List at 1 before being passed is ... "<< list[1][0]<< endl;
    fiddleWithArray(*pointer);
    cout << "List at 0 after being passed is ... "<< list[0][0]<< endl;
    cout << "List at 1 after being passed is ... "<< list[1][0]<< endl;
}

使用std::array

会更好