简体   繁体   English

代码块在程序中显示错误,但我找不到它

[英]codeblocks shows error in a program but i can't find it

void PRINT_LCS(int b[][], string x, int i, int j){

    if(i==0 || j==0)
        cout<<x[0];

    if(b[i][j] == 1){
        PRINT_LCS(b, x, i-1, j-1);
        cout<<x[i];
    }
    else if(b[i][j] == 2)
        PRINT_LCS(b, x, i-1, j-1);
    else
        PRINT_LCS(b, x, i, j-1);
}

this is my program but i don't know why the first line has an error. 这是我的程序,但是我不知道为什么第一行有错误。 The error messages are given below: 错误消息如下:

error: declaration of 'b' as multidimensional array must have bounds for all dimensions except the first|
error: expected ')' before ',' token|
error: expected initializer before 'x'|

You have to pass the second (column) dimension of the 2D array when declaring an array in function arguments. 在函数参数中声明数组时,必须传递2D数组的第二个(列)维。 In your case: 在您的情况下:

void PRINT_LCS(int b[][COLUMN], string x, int i, int j) //replace column with the no of cols in your 2D array 

When you declare an unidimensional array as int b[] , the compiler does not know the size of that array, but it use b as a pointer of int and is able to access to its components, being the responsibility of the programmer to be sure that access is in the bound of the array. 当您将一维数组声明为int b[] ,编译器不知道该数组的大小,但是它将b用作int的指针,并且能够访问其组件,程序员有责任确保该访问位于数组的边界内。 So, this code: 因此,此代码:

void f(int b[]) {
    b[5] = 15;  // access to 5th element and set value 15
}

is equivalent to: 等效于:

void f(int *b) {
    *(b + 5) = 15; 
}

If you use a bidimensional array, the rows of the array is stored consecutively in memory, so the compiler needs to know the column size to access to an arbitrary element in the array. 如果使用二维数组,则数组的行将连续存储在内存中,因此编译器需要知道列大小才能访问数组中的任意元素。 (Is still responsibility of the programmer to be sure the access is not out of bound). (程序员仍然有责任确保访问没有超出范围)。 Now, this code: 现在,此代码:

void f(int b[][COLUMN_SIZE]) {
    b[5][3] = 15;  // access to 5th row, 3rd column and set value 15
}

is equivalent to: 等效于:

void f(int *b) {
    *(b + 5 * COLUMN_SIZE + 3) = 15;
}

But if you don't specify the column size, how the compiler know its size? 但是,如果不指定列大小,编译器如何知道其大小? This is generalizable for multidimensional array. 对于多维数组,这是通用的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM