Reputation: 3477
I have been following the book Flex & Bison from Levine and I see the following piece of code:
main(argc, argv)
int argc;
char **argv;
{
if(argc > 1) {
if(!(yyin = fopen(argv[1], "r"))) {
perror(argv[1]);
return (1);
}
}
yylex();
I find it little hard to understand this part, for example, the first line:
char **argv;
for what I can see it should be related to this part:
if(!(yyin = fopen(argv[1], "r")))
so I can interpret that it is reading an input operation, this because of the "r", and the argv[1]
refers to the input of a line by console. Is it like that? I have no clue why the author is using a double pointer to argv. I suppose that when there is not a valid input it prints a descriptive error with perror()
, but in which case this could happen?
Upvotes: 1
Views: 118
Reputation: 986
The char **argv
is interpreted by the C++ compiler as the same as char* argv[]
, i.e, a pointer to an array of pointers. As you may already know, argv
represents the arguments passed to the program executable, e.g. ./program arg1 arg2
. You can think of argv
as an array of strings (C-strings) if that simplifies things, each element of the array is an argument.
Your interpretation is basically right. It checks that there is at least one argument argc > 0
(argument count), then uses the first argument (argv[1]
as argv[0]
actually refers to the program name ./program
) as a file name. It then tries to open a file of name argv[1]
for reading. If this fails, the fopen
returns NULL
. This can happen if the file doesn't exist.
Upvotes: 1