Reputation: 130
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.
Upvotes: 0
Views: 740
Reputation: 134326
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 membersargv[0]
throughargv[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 asint
, or the type ofargv
can be written aschar ** argv
, and so on.
Upvotes: 2