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

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

本文关键字:找不到 错误 显示 程序 代码      更新时间:2023-10-16
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);
}

这是我的程序,但我不知道为什么第一行有错误。错误消息如下所示:

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'|

在函数参数中声明数组时,必须传递 2D 数组的第二个(列)维度。在您的情况下:

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

当你将一个一维数组声明为 int b[] 时,编译器不知道该数组的大小,但它使用 b 作为 int 的指针并能够访问其组件,程序员有责任确保访问在数组的边界内。所以,这段代码:

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

相当于:

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

如果使用二维数组,则数组的行将连续存储在内存中,因此编译器需要知道列大小才能访问数组中的任意元素。(程序员仍然有责任确保访问没有越界)。现在,这段代码:

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

相当于:

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

但是,如果不指定列大小,编译器如何知道其大小?这对于多维数组是可推广的。