0

If I have a array of char array char *str[] = {"qwe", "asd", ..., "hello", "there" ,"pal"};

How would I pass that array but with specific range to a function (specifically execv), like pass in only "asd" till "hello"?

I know you can pass in something like str+1 to get skip the first. Is this possible?

user10416282
  • 33
  • 1
  • 7
  • Possible duplicate of [Pass in part of an array as function argument](https://stackoverflow.com/questions/38548759/pass-in-part-of-an-array-as-function-argument) – bishop Feb 21 '19 at 05:09
  • 3
    As you say, you could pass a pointer `char **ptr` pointing to the `"asd"` entry and say N values (so that `ptr[N]` points to `"hello"`). However, you have to copy those pointers somewhere before you use them with `execv()` because it requires a null-pointer terminated list. Or you need permission to replace `"there"` with a NULL pointer. – Jonathan Leffler Feb 21 '19 at 05:09
  • @bishop that doesn't fully apply here, as the array in that question is not sentinel-terminated. – Antti Haapala -- Слава Україні Feb 21 '19 at 05:22
  • 1
    You pass `str + start` and an integer indicating how long you want the range to be. There are no variable length arrays in C. – sudo Feb 21 '19 at 05:36
  • @sudo of course there are variable-length arrays in c. They're even called...*variable-length arrays". And as already stated by Jonathan, that's not how `execv*` works – Antti Haapala -- Слава Україні Feb 21 '19 at 06:15
  • @AnttiHaapala The "variable-length arrays" in C aren't what you'd expect from variable length arrays. You can't pass them into other functions and have them know the length unless you use a sentinel or something. – sudo Mar 03 '19 at 03:19
  • @sudo that's not the question here. They're arrays and their length is a variable and they're called variable-length arrays. – Antti Haapala -- Слава Україні Mar 03 '19 at 08:10

1 Answers1

2

You cannot do this for execv() as the manpage says:

The list of arguments must be terminated by a null pointer, and, since these are
       variadic functions, this pointer must be cast (char *) NULL.

The usage of str in execv() is like the following example

void func1(char *str[])
{
    for(int i=0; str[i]!=NULL; i++)
        printf("%s:%s\n", __func__, str[i]);
}

However, if the function has a declaration and usage like:

void func2(char *str[], int n)
{
    for(int i=0; i<n; i++)
        printf("%s:%s\n", __func__, str[i]);
}

you can call it as the following to pass in only "asd" till "hello".

func2(str+a, n);
//where str[a] is "asd" and str[a+n-1] is "hello"
KL-Yang
  • 381
  • 4
  • 8