开发者

Pass argv[1] by reference

I've an issue with passing argv to a function. Basically, I want to pass &argv[1] to the function and work from that. However, I don't understand why the foll开发者_如何学Goowing does work:

    void fun(char**&argv, const int& argc);

    int main(int argc, char** argv)
    {
            fun(++argv, --argc);
            return 0;
    }

yet the following doesn't work:

    void fun(char**&argv, const int& argc);

    int main(int argc, char** argv)
    {
            fun(&argv[1], --argc);
            return 0;
    }


Prototype:

void myfunc (char **argv, int argc)

Example usage:

  myfunc (argv, argc)

If you wanted to pass ONLY one string (argv[1]):

void myfunc (char *arg, int argc)
...
myfunc (argv[1], argc)

And if you wanted to pass an array of strings starting at argv[1]:

void myfunc (char **arg, int argc)
...
myfunc (&argv[1], argc)


The error I get when I try this is that argv[1] is a temporary value and you can't assign that to a non-const reference. If you instead do this:

void fun( char** const&argv, const int& argc);

Then either ++argv or &argv[1] will work.

Obviously, if you planned to actually change the value of argv itself, this won't work, but I presume that you aren't planning to do this since you're not passing a reference to argv itself but rather to the memory location of the second entry in argv.

The reason that the first one works and the second doesn't is that the ++ operator at the front modifies the variable and then returns not just its value after the modification, but the variable itself. As a result, the variable can then be passed into fun as a reference. But the &argv[1] is just the value of a memory location. It's a computed value, not a variable in its own right, so it can't be passed in as a non-const reference.

If you're planning to try to change the value of argv itself (to point it to a different array of character arrays), then &argv[1] doesn't work for that anyway, since it's not argv. ++argv, however, is argv, just after it's had its value adjusted.

You could also handle all of this without references at all, which would make things much easier, but that's up to you. If it were my code, though, I wouldn't be using references here. The const reference to an int could just be passed by value (which would be easier) and passing a reference to a double pointer doesn't save you any null checking (as it could still well be null). So there isn't much point to it. But if you like your code to be complex, feel free.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜