Code:
#include <stdio.h>
#include <stdlib.h>

main(char * argv[], int argc)

{   
   printf ("%d \n", argc);
}


Why is the output a random number? Yet, in this program, it works just fine:


Code:
#include <stdio.h>
#include <stdlib.h>

main( int argc, char * argv[])
{

   int a, i;
   
   

   
   for (a = 1, i=0; a<=argc ; a++ , i++)
    printf("%s \n", argv[i]);
   
    printf("%d \n", argc);
}


---

I figured it out, it works if I write main(int argc, char * argv[]) and not the other way around, like in the first code. Why does this happen?
Just imagine one second you are writing two functions with the same code and the same two arguments but swapped. For example:
Code:
int sub1(int a, int b) {
  return a-b;
}

int sub2(int b, int a) {
  return a-b;
}

Are you surprised that sub1(3,1) is different from sub2(3,1) ?
Ahh, so the first argument that is sent to main is always argc and the second one is always argv?
The arguments passed to the main function are standardized and are available for use by the OS or other calling code. C11 standard requires platforms have available int main(void) and int main(int argc, char* argv[]). C++ is essentially the same.
Yes, the argument order in this case is always the same and isn't influenced by the variable names. The names just allow you to refer to the arguments, but the OS always passes them in a specific order.
okay, thanks Travis
Correct - the random values you were getting in what you perceived to be "argc" were actually just bits of data in memory locations that the OS was sending via the *argv array Smile
  
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.

» Go to Registration page
Page 1 of 1
» All times are UTC - 5 Hours
 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

 

Advertisement