开发者

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

开发者 https://www.devze.com 2022-12-12 00:37 出处:网络
I realise thi开发者_高级运维s 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

I realise thi开发者_高级运维s 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?


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.


That's what argc is.

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

This will correctly print all arguments/


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消