Reputation: 244
Speaking of C
I know that
void main (int argc, char *argv[])
is the correct way to pass arguments to main,
but out of curiosity i wrote
void main (int argc, char *argv[1])
and the program, after compilation showed the exact same result as previous one.
What exactly i did in second version, can somebody explain me that?
thanks in advance.
Upvotes: 1
Views: 2152
Reputation: 1937
First, speaking of C, return type of main()
should be int
.
This is from the C language standard:
5.1.2.2.1 Program startup
1. The function called at program startup is namedmain
. The implementation declares no prototype for this function. It shall be defined with a return type ofint
and with no parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as
argc
andargv
, though any names may be used, as they are local to the function in which they are declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent; or in some other implementation-defined manner.
Second, char *argv[]
is there to allow for multiple command line arguments. Although char *argv[0]
looks strange but valid, it is common to leave to your command line argument parser dealing with this programmatically.
Here is a code example demonstrating that char *argv[0]
does not affect command line argument parsing:
#include <stdio.h>
int main(int argc, char *argv[0])
{
for (int i = 0; i < argc; i++)
printf("%s\n", argv[i]);
return 0;
}
Upvotes: 0
Reputation: 123448
In the context of a function parameter declaration, T a[N]
and T a[]
are both equivalent to T *a
; they declare a
as a pointer to T
.
In the case of argv
, T
is char *
.
If T
is an array type R [M]
, then R a[N][M]
and R a[][M]
are equivalent to R (*a)[M]
; they declare a
as a pointer to an array of R
.
Upvotes: 0
Reputation: 121377
void main (int argc, char *argv[1])
and
void main (int argc, char *argv[])
are equivalent.
argv
is a pointer (char**
) and the size specified for it in main()
is not the actual size of strings in argv
-- because an array passed to a function gets converted into a pointer to its first element. Basically the size value is ignored by the compiler.
For the same reason, you can specify:
void main (int argc, char *argv[101])
and it will still work as you'd expect. It can be confusing for anyone reading the code. But it's perfectly valid.
Relevant post: What is array decaying?
Upvotes: 7