views:

309

answers:

4

I realise this is an incredibly noob question, but I've googled for it and can't seem to find an answer (probably because I've worded the question wrong... feel free to fix if I have)

So I have this code:

int main(int argc, char* argv[])
{
    puts(argv[1]);
    return 0;
}

It works fine if I've passed a parameter to my program, but if I haven't, then obviously it's going to fail since it's trying to index a non-existent element of the array.

How would I find how many elements in in my string array?

+8  A: 

That's what argc is for. It holds the number of elements in argv. Try to compile and run this:

#include <stdio.h>
int main(int argc, char* argv[]) {
    int i;
    if (argc < 2) {
        printf ("No arguments.\n");
    } else {
        printf ("Arguments:\n");
        for (i = 1; i < argc; i++) {
            printf ("   %d: %s\n", i, argv[i]);
        }
    }
    return 0;
}

Test runs:

pax> ./prog
No arguments.
pax> ./prog a b c
Arguments:
   1: a
   2: b
   3: c

The argv array ranges from argv[0] (the name used to invoke the program, or "" if it's not available) to argv[argc-1]. The first parameter is actually in argv[1].

The C++ standard actually mandates that argv[argc] is 0 (a NULL pointer) so you could ignore argc altogether and just step through the argv array until you hit the NULL.

paxdiablo
Oh. I can't believe I did not see that... I feel like a total idiot now :(
Charlie Somerville
A: 

argc is a number of parameters. note that your app's name is a parameter too ;-)

Zepplock
Technically argv[0] is note necessarily the app name. It is an OS specific string that represents the application (which may or may not be absolute or relative).
Martin York
Agreed. Considering the content of the question - I was trying to simplify ;-)
Zepplock
A: 

The answer is contained in argc. NumOfParamaeters = argc-1;

Traveling Tech Guy
+1  A: 

That's what argc is.

for (int j = 0;  j < argc;  ++j)
    puts (argv [j]);
return 0;

This will correctly print all arguments/

wallyk