Re: passing arg char[X][Y] to function expecting (char**)
From: E. Robert Tisdale (E.Robert.Tisdale_at_jpl.nasa.gov)
Date: 01/28/05
- Next message: aegis: "Re: some help pls"
- Previous message: bob_jenkins_at_burtleburtle.net: "passing a (const void *) into memset()"
- In reply to: MackS: "passing arg char[X][Y] to function expecting (char**)"
- Next in thread: Keith Thompson: "Re: passing arg char[X][Y] to function expecting (char**)"
- Reply: Keith Thompson: "Re: passing arg char[X][Y] to function expecting (char**)"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Thu, 27 Jan 2005 15:32:37 -0800
MackS wrote:
> I've come across the following difficulty, related to questions 6.12,
> 6.13 and 6.18 in the FAQ, which I am unable to overcome:
>
> void fun(char **array_of_strings, int num_elements);
This is the same as
void fun(char* array_of_strings[], int num_elements);
>
> int main(int argc, char* argv[]) {
>
> char static_array_of_strings[NUM_STRINGS][MAX_STRING_LEN+1];
>
> fun((char**)&static_array_of_strings, NUM_STRINGS);
This should be something like
char* static_array_of_strings = {"s1", "s2", "s3"};
fun(static_array_of_strings, 3);
>
> return 0;
> }
>
> This code compiles but is wrong (I get a segmentation fault).
> How can I correctly call fun on static_array_of_strings?
>
> I can't modify the prototype of fun() because it also receives "true"
> char** (in the sense of dynamically allocated arrays of strings, ie,
> both the number of elements in the array
> as well as the length of each string
> are unknown size at compile time).
>
> How can I pass static_array_of_strings to it?
> The way I read FAQ 6.18 suggests this is impossible
> and the prototype of fun() would have to modified
> to include MAX_STRING_LEN+1.
You can write
char* array_of_strings
= (char*)malloc(NUM_STRINGS*sizeof(char*));
for (size_t i = 0; i < NUM_STRINGS; ++i)
array_of_strings[i] = &(static_array_of_strings[i][0]);
fun(array_of_strings, NUM_STRINGS);
free((void*)array_of_strings);
assuming that each array of char in static_array_of_strings
contains at least one '\0'.
If you have a C99 compiler, you could write a wrapper function:
void
fun2(size_t strings, size_t length,
char* static_array_of_strings[strings][length]) {
char* array_of_strings[strings];
for (size_t i = 0; i < strings; ++i)
array_of_strings[i] = &(static_array_of_strings[i][0]);
fun(array_of_strings, strings);
}
using variable size arrays.
- Next message: aegis: "Re: some help pls"
- Previous message: bob_jenkins_at_burtleburtle.net: "passing a (const void *) into memset()"
- In reply to: MackS: "passing arg char[X][Y] to function expecting (char**)"
- Next in thread: Keith Thompson: "Re: passing arg char[X][Y] to function expecting (char**)"
- Reply: Keith Thompson: "Re: passing arg char[X][Y] to function expecting (char**)"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|