Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 940
thlgood Avatar asked Apr 29 '12 01:04

thlgood


People also ask

Is argv a pointer C?

Because argv is a pointer to pointer to char , it follows that argv[1] is a pointer to char . The printf() format %s expects a pointer to char argument and prints the null-terminated array of characters that the argument points to.

Is argv a pointer or array?

The second parameter, argv (argument vector), is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.

What is the meaning of char * argv []?

The declaration char *argv[] is an array (of undetermined size) of pointers to char , in other words an array of strings. And all arrays decays to pointers, and so you can use an array as a pointer (just like you can use a pointer as an array).

What is argv array?

The argv parameter is an array of pointers to string that contains the parameters entered when the program was invoked at the UNIX command line. The argc integer contains a count of the number of parameters. This particular piece of code types out the command line parameters.


2 Answers

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]);
like image 125
Sergey Kalinichenko Avatar answered Oct 10 '22 00:10

Sergey Kalinichenko


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]);
}
like image 45
alf Avatar answered Oct 10 '22 00:10

alf