Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is argv[argc] equal to NULL Pointer [duplicate]

Tags:

c

linux

argv

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;
}
like image 482
dimSutar Avatar asked May 07 '13 12:05

dimSutar


People also ask

Does argc count null?

Yes, argv[argc] is guaranteed to be a null pointer.

Are argv arguments null terminated?

The argv parameter is an array of pointers to null-terminated strings representing the program arguments. Each element of the array points to a string representation of an argument passed to main (or wmain ).

What is the difference between argv and argc?

The first parameter, argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. The second parameter, argv (argument vector), is an array of pointers to arrays of character objects.

Can argv be null?

The argv[0] argument is a pointer to a character string containing the program name. The last element of the array pointed to by argv is NULL (argv[argc] is NULL). Arguments containing blanks can be passed to main() by enclosing them in quote characters (which are removed from that element in the argv vector).


2 Answers

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.

like image 90
rubenvb Avatar answered Sep 28 '22 01:09

rubenvb


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).

like image 21
Michael Foukarakis Avatar answered Sep 28 '22 02:09

Michael Foukarakis