开发者

Passing a pointer to an array of arrays of chars to a function?

开发者 https://www.devze.com 2023-02-16 20:47 出处:网络
For the assignment I am working on, I am required to use functions to manipulate data in an array of strings. So really, an array of arrays of chars. I define the array like so:

For the assignment I am working on, I am required to use functions to manipulate data in an array of strings. So really, an array of arrays of chars. I define the array like so:

char strings[5][100];

So there are presumably 500 contiguous chars in memory. The function I have defined looks like this:

void foo(char *labels[100]);

I think I might have some syntax issues here, but what I think this is doing is saying, 开发者_C百科"I'm a function that expects a pointer to an array of 100 chars." So labels* would point to the first array of chars, and (labels + 1)* would point to the second, and so on. I am calling the function like this:

foo(&strings[0]);

What I think this is doing is grabbing the address of the first array of chars in strings. The error message I'm getting tells me the function expects char ** but the argument is char (*)[100]. This is confusing to me as nowhere did I specify that there be a pointer to a pointer of a char.

Any help is greatly appreciated, or if you could pointer me in the right direction :)


strings is a two dimensional array. So it decays to char(*)[100] when passed to a function. Instead you can have the prototype like -

void foo(char labels[][100], int row); // `row` decides which param to access.

void foo(char labels[][100], int row)
{
    for(int i = 0; i < 100; ++i) // If you need, modify all the 100 row elements
    {
        labels[row][i] = 'a'; // Modifying like this
        // ....
    }
}


char strings[5][100]

declares strings as an array with 5 elements. Each element is an array of 100 chars.

void foo(char *labels[100]);

declares foo as a function that returns void and accepts an array of pointers. (the 100 is merely decorative: leaving it blank or putting 42 or 10000 is the exact same thing)

You want

void foo(char (*labels)[100]);

where the parameter is a pointer to arrays of exactly 100 chars.

0

精彩评论

暂无评论...
验证码 换一张
取 消