473,322 Members | 1,417 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

Why main() works also only with argc but not argv?

I am confused in command line arguments to a C program a little bit.
The argc maintains the count of the arguments passed and argv is array of vector to these arguments.But when i do :
Expand|Select|Wrap|Line Numbers
  1. void main(int argc)
  2. {
  3. printf("%d\n",argc);
  4. }
  5.  
It does the required job.But if i do:
Expand|Select|Wrap|Line Numbers
  1. void main(char **argv)
  2. {
  3. printf("%s\n",argv[0]);
  4. }
  5.  
i get a warning and segmentation fault.
Looks like main has been overloaded as:

Expand|Select|Wrap|Line Numbers
  1. void main();
  2. void main(int argc);
  3. void main(int argc,char **argv);
  4.  
Is it?
Mar 6 '11 #1

✓ answered by jjdot

Main is guessed to receive (at least) 2 arguments. Even if you can declare it with less arguments, the main function is called with the number of arguments and the array of arguments as parameters. Thus if 'main' is declared with
only 1 parameter this one receives (up to a cast) the number of arguments. In your second example, argv is assigned the number of arguments (+1 for the command name). So *argv[0] reads at address 1 which yields the
segfault.

10 2627
jjdot
11
Main is guessed to receive (at least) 2 arguments. Even if you can declare it with less arguments, the main function is called with the number of arguments and the array of arguments as parameters. Thus if 'main' is declared with
only 1 parameter this one receives (up to a cast) the number of arguments. In your second example, argv is assigned the number of arguments (+1 for the command name). So *argv[0] reads at address 1 which yields the
segfault.
Mar 6 '11 #2
i am sorry i didnt get you,you said atleast 2 arguments,what other arguments can be passed to main?how?
Mar 7 '11 #3
jjdot
11
You can have a third argument that contains environment
variables; it is a NULL terminated array of strings.

int main (int argc, char **argv, char **env);

I had never seen any program using it. Perhaps because
you have to parse yourself strings in 'env'. Each string
has the form VARNAME=VALUE. The function 'getenv' is more
convenient to check the value (and even existence) of an
environment variable.
Mar 7 '11 #4
Ohk,didnt knew about that.But as you are saying ATLEAST 2 arguments is what i am not getting.
as i have observed that
Expand|Select|Wrap|Line Numbers
  1. void main(int argc)
  2.  
works fine!.Then why not
Expand|Select|Wrap|Line Numbers
  1. void main(char **argv)
works?
Mar 7 '11 #5
jjdot
11
Because the parent process of your program calls it with
the 3 arguments by convention ! You can write for instance:

Expand|Select|Wrap|Line Numbers
  1. struct t {
  2.   double x;
  3. };
  4.  
  5. int main(struct t t)
  6. {
  7.   return 0;
  8. }
  9.  
Your compiler should accept this program (perhaps with
a warning). Then if you execute your program:

myprog bla bla arg!

Who knows how to convert arguments bla bla arg! into a struct t ? Nobody. When your program is started, after initialization steps, 'main' is called with convention arguments argc, argv and env. If you have created a function whose prototype is not compatible with the convention don't be surprised to have a SegFault. The convention is that 1st argument is an integer, 2nd and 3rd are arrays of strings. So if you use this prototype:

Expand|Select|Wrap|Line Numbers
  1. void main(char **argv)
You are wrong. Pointer argv receives the value of argc.
And thus reading cell argv[0] has no sense.
Mar 7 '11 #6
Banfa
9,065 Expert Mod 8TB
According to the C standard there are 2 defined prototypes for main

int main()

and

int main(int argc, char* argp[])

The C standard (but not the C++ standard) does allow compilers to implement other prototypes but you would need to look in the compiler documentation to find out what they are, for example Microsoft does support

int main(int argc, char* argp[], char* envp[])

as already stated.

If its not in the standard and its not in the compilers documentation then it is undefined behaviour and should be avoided.

For example

void main(int argc);

is not defined in the standard, and (assuming you are using Visual Studio) is not defined in Microsofts documentation. It should not be used.
Mar 7 '11 #7
weaknessforcats
9,208 Expert Mod 8TB
Speaking of Visual C++, you can set a project property to replace main() with any function of your choice as the entry point function. main(int, char**) is just the default.
Mar 7 '11 #8
Ok,so compiler expects me to write main() as either of the following:
Expand|Select|Wrap|Line Numbers
  1. 1.void main(){}
  2. //I can use neither argc,argv nor env 
  3.  
  4. 2.void main(int argc){}
  5. //I can only use argument count,but not argv or env
  6.  
  7. 3.void main(int argc,char **argv)
  8. //I can use argument count, argv but not env
  9.  
  10. 4.void main(int argc,char **argv, char **env)
  11. I can access all.
  12.  
  13.  
No other form of main is allowed.Even if i want to do something stupid like:
Expand|Select|Wrap|Line Numbers
  1. void main(char **argv,char **env) NOT ALLOWED RIGHT?
  2.  
Mar 10 '11 #9
jjdot
11
It is a good summary but to prevent portability problems
you should use either 3 or 4 forms.
Mar 10 '11 #10
Banfa
9,065 Expert Mod 8TB
No main always... ALWAYS returns int and none of your prototypes show that.

From the C standard you can use the following

Expand|Select|Wrap|Line Numbers
  1. 1.int main(){}
  2. //I can use neither argc,argv nor env 
  3.  
  4. 2.int main(int argc,char **argv)
  5. //I can use argument count, argv but not env
  6.  
From the Microsoft documentation you can use the extension

Expand|Select|Wrap|Line Numbers
  1. 3.int main(int argc,char **argv, char **env)
  2. // I can access all.
  3.  
http://msdn.microsoft.com/en-us/library/3ze4ytsc.aspx

You should not rely on anything else working.
Mar 10 '11 #11

Sign in to post your reply or Sign up for a free account.

Similar topics

6
by: Thomas Mlynarczyk | last post by:
Hello! I run PHP 4.3 as an Apache module. I use Apache 1.3 as a service under WinXP. And I've got a strange problem with exec(): The following commands are executed correctly:...
6
by: mg | last post by:
Hello, I am writting bindings for a FEM application. In one of my function 'initModulename', called when the module is imported, I would like to get the argc and argv arguments used in the main...
1
by: Angelos | last post by:
Why does this Script does not work in Firefox ? I am trying to make a select deselect CHECKbox function with invert selection capability... But this script works only in IE :( Any Help and...
14
by: Hal Styli | last post by:
Is this a style thing? int main(int argc, char *argv ) or int main(int argc, char **argv ) i.e. *argv or **argv Why choose the latter?
4
by: Xog Blog | last post by:
Hi I am by some people's standards a newbie to C, and I am refreshing my memory as to some of its conventions. I would like any patient soul out there to help out. I am having a horrible time...
25
by: Michal Kwiatkowski | last post by:
Hi, Code below shows that property() works only if you use it within a class. ------------------------------------------------ class A(object): pass a = A() a.y = 7
4
by: artur.siara | last post by:
Hello, I want to remove from string a <span> tag, but with leave the value of that tag. I have that code: theExp = new RegExp("<span>", "g"); txt = txt.replace(theExp, "");
0
by: tiggman | last post by:
Why preg_split works only if the char # before the delimiter is 21 or less? example php code: ============= $right = "{Hello Im very aaaaaa {cool|not cool}}"; print $right."<br>"; $pattern =...
2
by: sunday | last post by:
When trying to update a table, the following works only occasionally; it doesn't work reliably. Can anyone show me where I'm going wrong, please? // $commenrts_new is the data from the form ;...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.