12

I read an article (forgot the URL), which said that argv[argc] is a NULL pointer (contains \0). To check whether if its true I wrote this code, yeah it exist. What I don't understand is, why does the OS include this NULL pointer at argv[argc]. Is it useful for something else also?

int
main (int argc, char **argv){

    while (*argv)
        printf ("%s\n", *argv++);

    return 0;
}
X. Liu
  • 1,070
  • 11
  • 30
dimSutar
  • 1,425
  • 2
  • 13
  • 17
  • "*argv[0] shall be the pointer to the initial character of a NTMBS that represents the name used to invoke the program or "". The value of argc shall be nonnegative. The value of argv[argc] shall be 0.*" – Maroun May 07 '13 at 12:26

2 Answers2

11

The C Standard 5.1.2.2.1/2 second mark says explicitly

argv[argc] shall be a null pointer.

The C++ Standard 3.6.1/2 also says explicitly

The value of argv[argc] shall be 0.

rubenvb
  • 74,642
  • 33
  • 187
  • 332
  • Yes, but what is the motivation for this? – Thilo May 07 '13 at 12:28
  • Why is the sky blue? It's a null terminated array of null terminated arrays of `char`. I'd guess consistency and to facilitate code like the OP wrote. – rubenvb May 07 '13 at 12:29
  • See, you can do it. :-) Sounds like a good answer to me. – Thilo May 07 '13 at 12:32
  • 1
    As for your question about the colour of the sky: http://www.sciencemadesimple.com/sky_blue.html – Thilo May 07 '13 at 12:34
  • 1
    @rubenvb http://math.ucr.edu/home/baez/physics/General/BlueSky/blue_sky.html :D – Maroun May 07 '13 at 12:34
  • 1
    @MarounMaroun slowpoke :) – sehe May 07 '13 at 12:35
  • According to me such rules are really helpful in writing better efficient code. And I guess only this is the reason why they included it. Thank you everyone. Have a great day. – dimSutar May 07 '13 at 12:36
  • 2
    This is what happens when the question title does not reflect the question body. @Thilo: Also: why then is the sky not violet? **Edit:** I see the second link intelligently answers that one. – rubenvb May 07 '13 at 12:38
  • @rubenvb 2 in 1: http://answers.yahoo.com/question/index?qid=20090208215127AAdL1E6 But the first link I provided answers this. – Maroun May 07 '13 at 12:40
  • http://physics.stackexchange.com/questions/28895/why-is-the-sky-not-purple – Thilo May 07 '13 at 12:40
  • 1
    Regarding blue sky: https://xkcd.com/1145/ – hlovdal May 07 '13 at 12:45
  • 2
    I'm going to have to find better rethorical questions. – rubenvb May 07 '13 at 12:54
5

The Standard (C99 5.1.2.2.1p2) mandates that:

If they are declared, the parameters to the main function shall obey the following constraints:

— The value of argc shall be nonnegative.

— argv[argc] shall be a null pointer.

...

The rationale for this is to provide a redundant check for the end of the argument list, on the basis of common practice (ref: Rationale for the ANSI C programming language (1990), 2.1.2.2).

Michael Foukarakis
  • 39,737
  • 6
  • 87
  • 123