[Solved] How to choose types for a function prototype?


I’m going to suppose that you are trying to make a deep copy of the argv array, with that being a NULL-terminated array of strings such as the second parameter of a C program’s main() function. The function you present seems to assume that you have already allocated space for the destination array itself; its job seems limited to copying the argument strings.

First things first, then: let’s look at the caller. If you’re making a deep copy of a standard argument vector, then the type of the destination variable should be compatible with the type of argv itself (in the colloquial sense of “compatible”). If the lifetime of the copy does not need to extend past the host function’s return, then a variable-length array would be a fine choice:

char *copy[argc + 1];

That relieves you of manually managing the memory of the array itself, but not of managing any memory uniquely allocated to its elements. On the other hand, if you need the copy to survive return from the function in which it is declared, then you’ll have to use manual allocation:

char **copy = malloc((argc + 1) * sizeof(*copy));
if (!copy) /* handle allocation failure */ ;

Either way, you can pass the resulting array or pointer itself to your write_command() function, and the required parameter type is the same. It is pointless to pass a pointer to copy, because that function will not modify the pointer it receives as its argument; rather, it will modify the memory to which it points.

Here is the signature of the function you seem to want:

void write_command(char *argv[], char *string[]) {

Given such a signature, you would call it as …

write_command(argv, copy);

….

The key step you seem to want to perform in the loop inside is

    string[r] = strdup(argv[r]);

You can accomplish the same thing with a malloc(), initialize, strcpy() sequence, but that’s a bit silly when stdrup() is ready-made for the same task. Do not forget to check its return value, however, (or in your original code, the return value of malloc()) in case memory allocation fails. Any way around, you must not free the allocated memory within write_command(), because that leaves you with invalid pointers inside your copied array.


Furthermore, even if you really do have a 2D array of char * in the caller, such as …

char *copies[n][argc + 1];

nothing changes with function write_command(). It doesn’t need to know or care whether the array it’s copying into is an element of a 2D array. You simply have to call it appropriately, something like:

write_command(argv, copies[w]);

No matter what, you must be sure to free the copied argument strings, but only after you no longer need them. Again, you cannot do that inside the write_command() function.

0

solved How to choose types for a function prototype?