1

所以我以某种方式让这个工作,我真的很感兴趣为什么我的第一次尝试失败了。

我有 C 的非正式经验,现在正在尝试学习 C++。我想我会尝试一些常见的命令,例如将参数传递给函数,但在尝试访问传递的数组的内容时收到“不完整的类型错误”。

这是错误的代码:

    void printoutarray(int array[][], int height, int width){
        for (int x = 0; x < width; x++){
            for (int y = 0; y < height; y++){
                cout << array[x][y]) << " ";
            }
            cout<<"\n";
        }
    }

我能够使用指针修复代码:

    void printoutarray(int *array, int height, int width){
        for (int x = 0; x < width; x++){
            for (int y = 0; y < height; y++){
                cout << *(array+x*width+y) << " ";
            }
            cout<<"\n";
        }
    }

并通过像这样传递数组:

    #define hght 5
    #define wdth 5
    /*Other code/main function*/
    int inputarray[hght][wdth] = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15},{16,17,18,19,20},{21,22,23,24,25}};
    printoutarray(*inputarray, hght, wdth);

但我的问题是为什么我必须专门向函数发送数组的指针。数组变量不应该是指针本身吗?另外,为什么我需要在我的“固定”代码中包含取消引用运算符,是因为我正在发送一个指针的指针吗?我再次对语言的工作原理感到好奇,所以任何见解都将不胜感激,谢谢!

4

2 回答 2

3

Arrays are converted to pointers when passed to a function (true in C and C++). Your mistake seems to be thinking that because of this a 2D array should be converted to a double pointer when passed to a function, that isn't true.

You have a 2D array

int inputarray[hght][wdth] = ...;

One way of looking at this is that it's an array of size hght, each element of this array is another array of size wdth. So when converting this array to a pointer, you get a pointer to an array of size wdth. Like this

void printoutarray(int array[][wdth], int height, int width){

or more explicitly like this

void printoutarray(int (*array)[wdth], int height, int width){

With either of these slight changes your original code will work. Though in both cases the width parameter is useless, because this function only works on arrays with width wdth

Nothing happening here that wouldn't also work exactly the same way in C.

于 2013-05-05T21:47:46.850 回答
0

Syntactial/typos aside, there is no essential difference between those two functions. The "pass by value" doesn't pass by value at all, just like C, it passes a pointer to the first element. I would be very surprised if the compiler output for the two functions you have given are different in any meaningful way.

于 2013-05-05T21:48:00.087 回答