6

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 ?

rath
  • 2,725
  • 1
  • 30
  • 48
Bin
  • 920
  • 2
  • 12
  • 23

2 Answers2

11

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 *

nos
  • 207,058
  • 53
  • 381
  • 474
  • @Bathsheba , exactly! – Bin Dec 11 '13 at 09:13
  • Means I have to parse '*' as *, -_- – Bin Dec 11 '13 at 09:14
  • 3
    No, you don't have to parse `'*'` as `*`. It's the shell that changes `*` to a list of files in the current directory and `'*'` (or `"*"`) to just `*`. So giving your program `'*'` from shell would give your program just one argument that contains `*` without quotes. – Shahbaz Dec 11 '13 at 09:16
  • 1
    To make the input as clean as possible, use e.g. `echo '1 2 * 3 *' | xargs ./test` - this is about as clean as `./test '1 2 * 3 *'`, but also fills the `argv` array properly – anatolyg Dec 11 '13 at 09:45
8

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

Bathsheba
  • 220,365
  • 33
  • 331
  • 451