0

I am trying to figure out what will be result of passing argv variable to main in this format. main( int argc, char const * argv ).

I know right way of using it is main( int argc, char const **argv) or main( int argc, char const *argv[]).

Here is my code snippet,

#include <stdio.h> int main( int argc, char const * argv ) { for( int i = 0; i < argc; ++i ) { printf("%s\n", argv[i]); } } 

Here is output,

$ ./a.exe

..

$ ./a.exe 1

2

....

$ ./a.exe 1 2

2

...

Does it fetch from whatever, argv points? Why does it terminate before even reaching argc.

2
  • 1
    It's actually not the right way unless your implementation allows it. The C standard only specifies argv as a buffer of pointers to non-const strings. Commented Mar 21, 2017 at 16:31
  • In your code as written, argv[i] will be a char value. In the printf call, that will be promoted to an int value. However, the printf function is expecting a valid pointer to a null-terminated sequence of char at that position, not some bogus pointer value. Commented Mar 21, 2017 at 19:14

1 Answer 1

2

It causes undefined behavior as the supplied type and the expected type does not match thereby this is a clear case of constraint violation.

Quoting C11, chapter chapter §5.1.2.2.1/p2, (emphasis mine)

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

  • ...

  • If the value of argc is greater than zero, the array members argv[0] through argv[argc-1] inclusive shall contain pointers to strings, which are given implementation-defined values by the host environment prior to program startup

You can re-write char * argv[] as char **argv NOTE considering the array decay property, but a char *[] and a char * are not compatible in any way.


NOTE:

Quoting C11, chapter §5.1.2.2.1, footnote 10)

Thus, int can be replaced by a typedef name defined as int, or the type of argv can be written as char ** argv, and so on.

Sign up to request clarification or add additional context in comments.

1 Comment

Additionally, the printf call has undefined behavior because the types of the arguments differ from those specified by the format specifier string.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.