No of elements wich will passed by *argv[] in main()

I read at https://en.cppreference.com/w/cpp/language/main_function
that argv should hold argc+1 pointers, whereby the last should be '\0'.
So I made the short program below for testing this.
But when it comes to reading the argc+1th pointer, I get a segfault, the debugger claims that argv holds only arc elements.

So is there an error at the description page, or do I reflected the stuff in a wrong manner?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

int main( int argc, char *argv[] )
{
    using namespace std;
    
    cout << argc << endl;
   
   // Printing all cstrings which argv should contain:
   // ( https://en.cppreference.com/w/cpp/language/main_function )
   
   for( int i = 0; i < argc+1; ++i )
   {
       char *p = argv[i];
       
       do {
            cout.put(*p);
       } while( *p++ );  // till '\0'
   }
}
The last argument isn't a pointer to an empty string ('\0'), it is a NULL pointer.

So yes, instant segfault if you try to access it.

and the last element, argv[argc], is guaranteed to be a null pointer.

Thank you salem c!
false == '\0' == 0 == NULL and I think also == NULLPTR but not sure. Sometimes web-code uses the wrong representation of a zero to get the right answer, in misleading ways. You can just as easily iterate it as a pointer until it is 'false' and it will work if you are trying to make an entry for a convoluted code contest. But that '\0' is probably saying 'null' not 'empty string. An empty string isnt null, it has one character in it of a value of zero, in C strings. A lot of errors I have seen from people not understanding the difference between an empty c-string and a nonexistant one.
Last edited on
Topic archived. No new replies allowed.