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.
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.
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.
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).
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.
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]);
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]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With