user47322
user47322

Reputation:

Get the number of elements in a pointer to a char array in C++

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?

Upvotes: 1

Views: 1794

Answers (4)

paxdiablo
paxdiablo

Reputation: 881103

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.

Upvotes: 7

wallyk
wallyk

Reputation: 57774

That's what argc is.

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

This will correctly print all arguments/

Upvotes: 1

Traveling Tech Guy
Traveling Tech Guy

Reputation: 27811

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

Upvotes: 0

Zepplock
Zepplock

Reputation: 29135

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

Upvotes: 0

Related Questions