thlgood
thlgood

Reputation: 1295

a pointer about *argv[]

This is my main.c

......
int main(int argc, char **argv)
{
    init_arg(&argc, &argv);
    ......
}

This is my init_arg.c

......
void init_arg(int *argc, char ***argv)
{
    printf("%s\n", *argv[1]);
    ......
}

I compiler it with no error and warning.

I run it:

./a.out include

It get Segmentation fault

When I debug it, I found step printf("%s\n", *argv[1]);

get wrong, It show:

print *argv[1]

Cannot access memory at address 0x300402bfd

I want to know, How to print argv[1] in init_arg() function.

Upvotes: 14

Views: 1032

Answers (3)

torek
torek

Reputation: 488193

I'm assuming that the reason for passing &argc and &argv in the first place is so that you can update them inside init_arg. Here's how I prefer to write such functions, in general:

/*
 * init_arg: do something useful with argc and argv, and update argc and argv
 * before returning so that the caller can do something else useful that's
 * not shared with all the other callers of init_arg().
 * (this comment of course needs updating to describe the useful things)
 */
void init_arg(int *argc0, char ***argv0) {
    int argc = *argc0;
    char **argv = *argv0;
    ... all the operative code goes here, and then ...
    *argc0 = argc;
    *argv0 = argv;
}

Of course this means you must not do early returns inside init_arg, so there are some tradeoffs, but it sure is a lot easier to work with the same regular old argc and argv inside init_arg.

Upvotes: 2

alf
alf

Reputation: 681

Argv is already a pointer. Just pass it like this:

init_arg(&argc, argv);

And init_arg should look like this:

void init_arg(int *argc, char **argv) {
    printf("%s\n", argv[1]);
}

Upvotes: 13

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

You need to add a pair of parentheses around (*argv) to change the order of evaluation. The way you currently have it, the [1] is evaluated first, yielding an invalid pointer, which then gets dereferenced, causing undefined behavior.

printf("%s\n", (*argv)[1]);

Upvotes: 19

Related Questions