Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect command line arguments number when passing `*` [duplicate]

I'm writing a C program about Reverse Polish Notation, which takes its operands and operators through the command line arguments. But things go wrong when the multiply operator '*' occurs, and I don't know why.
Here is the little program to debug.

test.c

int main(int argc, char **argv)
{
    printf("%d\n", argc);
    return 0;
}

//   run case           result
    ./test a b            3
    ./test *              66

So why the '*' argument makes a wrong result ?

like image 691
Bin Avatar asked Dec 11 '13 09:12

Bin


2 Answers

The * does a shell glob. So it'll expand to all the files in your current directory, which will be the arguments to your program, you have 65 files in your directory. You can see what's happening if you run echo *

You need to single quote the * as in ./test '*' (double quotes would work too) , this will prevent the shell expanding *. A * is given to your program in this case, the shell removes the single quotes.

If you want to evaluate expressions, you could do

./test 3 2 '*'

In this case your program receives 3 additional arguments separated so argv[1] is 3, argv[2] is 2 and argv[3] is *

Or you could do:

./test '3 2 *'

In this case, your program receives 1 additional argument, argv[1] will be the string 3 2 *

like image 167
nos Avatar answered Nov 19 '22 03:11

nos


Your command shell is treating * as a wildcard. It's probably including every file in the current directory: 60ish in your case.

like image 8
Bathsheba Avatar answered Nov 19 '22 04:11

Bathsheba