How to declare char array as function parameter ?o

2020-04-01 07:41发布

问题:

What should I do to resolve this ?

i don't know any other way so i didn't try anything

bool isPresent(int p_rows,int p_cols,char p_search[p_cols'1']'2','3'char p_words[][p_cols])

The counting in single commas indicate which error I m receiving at which point. One more thing which I would like to mention is that I m doing recursion in this program and there are other functions also whose parameters are same as of this but only this function definition is causing errors

1)use of parameter outside function body before ']' token
2)expected ')' before ',' token`enter code here`
3)[Error] expected unqualified-id before 'char'

回答1:

Variable length arrays are not a standard C++ feature. However in this declaration

bool isPresent(int p_rows,int p_cols,char p_search[p_cols], char p_words[][p_cols]);
                                                   ^^^^^^                  ^^^^^^

you are trying to use variable arrays declarations.

For the last parameter declaration

char p_words[][p_cols]

the variable p_cols must be a compile-time constant.

The declaration can look the following way. I suppose that the array passed to the function as the last argument is declared in a program like an array with fixed constant dimensions and the variables p_rows and p_cols specify a sub-array of the array.

bool isPresent(int p_rows,int p_cols,char p_search[], char p_words[][N]);

where N is the second constant dimension of the original array.

For example

const size_t M = 100;
const size_t N = 100;

bool isPresent(int p_rows,int p_cols,char p_search[], char p_words[][N]);

int main()
{
    char p_words[M][N];
    char p_search[N];

    // ...    

    int p_rows = 10; 
    int p_cols = N;

    isPresent( p_rows, p_cols, p_search, p_words );

    //...
}

Otherwise you should use for example std::vector<std::vector<char>>, or std::vector<std::string>, or an array of std::vector<char>, or an array of std::string instead of your original array definition.



回答2:

declaring a character array as an argument is the same as declaring it as a variable.

for example, the array

char ch_array[SIZE];

can be declared as an argument for foo like that

void foo(char ch_array_arg[SIZE])

it can also be declared as a pointer to a sequences of characters as in

void foo(char *ch_array_arg);

of course in that example you will also have to specify the size of the array.