I've recently started learning C++ and I'm a bit confused about argv and argc. I am trying to determine if arguments were passed to a program by checking the size of argc, but no matter how many arguments (including none) I pass to the program the size of it is always 4.
Simple example:
int main(int argc, char** argv)
{
std::cout << sizeof(argc); //outputs 4 with 0 or any num of arguments
std::cout << sizeof(argv); //outputs 8 with 0 or any num of arguments
}
I found this same question asked before and I apologise for repeating it but the answers on those pages I found were contradictory to what's happening here.
So, why is argc always 4 and is there any other way to check if arguments were passed to main()?
If it's relevant I'm using g++ to compile.
sizeof(argc) will always be the same value. sizeof(variable_name) gives you the size that variable takes up in memory. If you want to know how many parameters were passed you need to evaluate what the variable contains. For instance
std::cout << argc - 1;
Will have it display how may parameters were passed. The - 1 is needed because the first parameter is the name of the program so we don't want count that in the parameter count.
I am trying to determine if arguments were passed to a program by checking the size of argc
argc is the number of arguments. The size of argc is the size of int object.
So, why is argc always 4
Because the size of int object is always 4 bytes on your system.
is there any other way to check if arguments were passed to main()?
You can check the value rather than the size of argc:
std::cout << argc;
Note that there is (typically) at least one argument to the program: The command that was used to execute it.
sizeof gives you, at compile time, the size of the enclosed type.
So sizeof(argc) is sizeof(int), and sizeof(argc) is sizeof(char**). I hope you appreciate this is therefore completely independent of the arguments passed!
Simply rely on what C++ gives you: argc is the number of arguments passed, including the program name. And the number of elements in argv is the same as argc, with an addional one which is set to nullptr.
Related
This question already has answers here:
What does int argc, char *argv[] mean?
(12 answers)
Closed 6 years ago.
I don't understand the following piece of code:
int main(int argc, char** argv)
{
// See if we've been given a seed to use (for testing purposes). When you
// specify a random seed, the evolution will be exactly the same each time
// you use that seed number.
unsigned int seed = 0;
for(int ii=1; ii<argc; ii++) {
if(strcmp(argv[ii++],"seed") == 0) {
seed = atoi(argv[ii]);
}
}
How can I pass a value to main function? I read a bit and found out that it is called parsing, could you please clarify what is it?
Thanks,
The parameters int argc and char** argv are automatically passed to main and are parsed from the command line used to invoke the program. They are, respective, the number of command line parameters including the program name itself and an array of pointers to C-style strings of these parameters. So if the following is used to invoke my_prog:
./my_prog file 10
main gets called with argc set to 3 and argv is a char* array of 3 pointers to "./my_prog", "file" and "10"
EDIT: thanks to #BasileStarynkevitch for pointing out on POSIX complaint systems argv will have an argc + 1 element of NULL to also indicate end of parameters.
I'm extremely new to Ubuntu and PuTTY and putting a C++ file into it, but I'm having a problem with my C++ file. What I need the program to do is take a string entered from the Ubuntu side, put into the C++ program, and have it count how many strings are entered in and it sends back like so:
./myfile Supplying arguments now
Argument #0: ./myfile
Argument #1: Supplying
Argument #2: arguments
Argument #3: now
Number of arguments printed: 4
So, when I run my program down below, the program goes on forever and I can't step through it. What is causing it and why and/or what can I do to fix the problem?
#include <stdio.h>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int count = 0;
while (*argv[argc] != NULL)
{
count++;
}
cout << count << endl;
system("PAUSE");
return 0;
}
Your code is an infinite loop because your while loop always checks the same condition. That's because argc never changes in your code.
What you meant to write is while (*argv[count] != NULL). However, what you meant isn't correct either.
C doesn't check array boundaries. When you read past an array boundary, you will not necessarily encounter a 0 value. You will read random garbage data which is in memory at that place.
You don't need to count the number of arguments yourself, because you already have it in the variable argc.
So a better solution to iterate all the command line arguments would be a for loop which increments count from 0 to argc.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
How does the main() function handle a variable number of arguments without the use of ellipses (...)? For processing variable number of arguments, last argument to the function should be ... which is not the case with the main() function.
Basically, main() is special, and it has two standard-defined forms:
int main(int argc, char **argv)
int main(void)
The system may support other forms; it is common that the environment is also made available:
int main(int argc, char **argv, char **envp)
These forms are fixed. The only unusual thing is that a system must support either of the first two (and some systems support others as well).
The variable number of command line arguments is handled via an array of pointers to strings (that's argv above), unlike say execl() from POSIX.
See also:
How does the main() function in C work?
What should main() return in C and C++?
rahul manglani commented:
The two links you mentioned made it pretty clear. There are different possible approaches listed there, which of them is actually being used is not mentioned.
In a sense, it doesn't matter; the system simply has to work, and the people who produce 'the system' must make it work. You as the programmer using the system don't need to know how it works; you can simply assume that it does work.
Behind the scenes, what usually happens is that the 'start' function which calls main() does some fixup work (in the case of a C++ program in particular, a lot of fixup work — such as ensuring all the constructors that must be executed before main() starts are in fact executed), but ends with a fixed sequence such as:
exit(main(argc, argv, environ));
Note that environ is a global variable, extern char **environ; (which is unique among the global variables defined by POSIX in that no header declares it) and it contains the pointers to the environment variables. The 'start' code has to ensure that is set; it is trivial to pass environ as an argument to main(), therefore.
This calls main() with a fixed argument list and calls exit() if/when it returns. Indeed, Apple takes it a step further and passes a fourth argument to main(). If the called function was defined as int main(void) { … }, it simply ignores the arguments it was passed; if it was defined as int main(int argc, char **argv) { … }, it can access the command line arguments as usual; if it was defined as int main(int argc, char **argv, char **envp) { … }, then it can access the environment too.
Generally, the systems are set up so that extra arguments don't cause damage. This is a reason why C is unusual in its calling conventions and it's why the called function doesn't clean up the arguments pushed onto the stack — the called function doesn't know how many arguments were actually pushed onto the stack. It assumes that the ones it expects were provided and uses those without problems, but the calling code knows what it pushed so it can clean up properly. The biggest problems occur if the called function expects N arguments but the caller passes M arguments and M < N. (There are also issues of types pushed and the sizes of those types, etc, but that's a second-order problem.)
In C/C++ main takes 2 parameters, typically called argc, and argv. The argv parameter is an array of argc char arrays. Command line arguments are passed to the program in argv. There are variations on this theme with the exact number of parameters, but main's signature is generally
int main(int argc, char **argv);
I interpreted this question to mean: how is it possible that main can take either zero arguments or two arguments?
While the details are obviously implementation-dependent, on most implementations, the default C calling convention is that the caller cleans the stack. Therefore, the code that calls main is at perfect liberty to always push two arguments onto the stack (argc and argv), whatever the declaration of main might be. If main is declared with no arguments, then main simply won't access the values of the arguments it receives. After main returns, the calling code clears the stack.
It should be pointed out that main isn't even special in this sense. Try this:
int printf();
int main() { printf("Hello, world!\n"); }
The C compiler will happily allow you to call printf even though, lacking an #include <stdio.h> directive, it has no idea how many arguments printf actually wants. Presumably, the code that calls main is conceptually something like this:
int main(int argc, char** argv); /* declare "main" */
main(argc, argv); /* call "main" */
If the definition of main actually specifies zero parameters, this still works (although I believe it would technically be undefined behaviour if you actually did this).
In the case of C++, although the linkage of main is left unspecified by the standard, most implementations simply treat it as though it has C linkage, so the name is not mangled and everything above still applies.
It handles it by accepting an array and array length set as variables argc and argv
you may find more data here:
http://crasseux.com/books/ctutorial/argc-and-argv.html
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
if i compile this code under Visual Studio 2013
int main(int argc, char* argv[])
{
std::cout << "arg count: "<< argc << "/n";
}
and then run it with no additional arguments (i.e. >program.exe), it outputs
arg count: 1
with 1 argument (>program.exe arg1) it outputs
arg count: 2
BUT this is where it gets weird. if i input (>program.exe arg1 arg2) it outputs
arg count: 2
"arg count" should be 3, shouldn't it?
with (>program.exe arg1 arg2 arg3) it outputs
arg count: 2
it should be 4 in this case...
printing argv[3] works fine for some reason.
why is this happening?
Section 3.6.1 of the C++ standard defines how main and its arguments work:
In the latter form, for purposes of exposition, the first function parameter is
called argc and the second function parameter is called argv, where argc shall be the number of arguments
passed to the program from the environment in which the program is run. If argc is nonzero these arguments
shall be supplied in argv[0] through argv[argc-1] as pointers to the initial characters of null-terminated
multibyte strings (ntmbs s) (17.5.2.1.4.2) and argv[0] shall be the pointer to the initial character of a
ntmbs that represents the name used to invoke the program or "". The value of argc shall be non-negative.
The value of argv[argc] shall be 0. [ Note: It is recommended that any further (optional) parameters be
added after argv. —end note ]
That means with a standard-conforming compiler, you should be able to access argv[argc].
Accessing argv[n] with n > argc is undefined though. It may crash, but doesn't have to.
What you're experiencing is weird, as apparently the arguments are processed as a single argument. If you provide the arguments exactly as stated, this should not happen.
You should fix the signature of main. The standard guarantees at least these two signatures, anything else is implementation-defined:
— a function of () returning int and
— a function of (int, pointer to pointer to char) returning int
As you want to access arguments, the appropriate signature is int main(int argc, char** argv).
ok, as it turns out, the problem was in some code i didn't include here. my code was:
if (argc = 2) { do some stuff }
it should have been
if (argc == 2) { do some stuff }
i feel really stupid :\
I can guess that either you enter as
(>program.exe "arg1 arg2"
or
(>program.exe arg1,arg2
This question already has answers here:
What is the proper declaration of main in C++?
(5 answers)
Closed 9 years ago.
So in my professor's slides he simply gives examples like:
main()
{...
}
Right? But when I put this in visual studio it gives an error and it works when I put int in front of main.
Why would my professor not put int in front of main?
Can main be any other type of variable?
Also I see a lot of int main(void). Why is this necessary? Can anything else be put in as a parameter?
main returns int. In older versions of C you could leave out the int and the compiler would pretend that you had said int. In C++, if 'main' doesn't explicitly return a value, it magically returns 0. You can return three values from main: 0, EXIT_SUCCESS, and EXIT_FAILURE. 0 is equivalent to EXIT_SUCCESS. The two named values are defined in <stdlib.h> and if you're coding in C++ in <cstdlib>.
The void is a C-style declaration that a function takes no arguments. In C++ you don't need it; a function that has no arguments in its declaration takes no arguments.
In general, though, main takes two arguments:
int main(int argc, char *argv[])
Those are the command-line arguments. argc is the number of arguments, and argv is an array of pointers to C-style strings that hold the arguments. The first string (argv[0]) is the name of the program.
Because you are using either: C++ or C99 or C11.
C89 had an implicit int rule that mades main() equivalent to int main(). This does not exist in C++ and no longer exists since C99.
As you mentioned you are using Visual Studio and it does not support C99 and C11, you are probably compiling your program with the C++ compiler and not the C compiler.
The standard form of the main function, traditionally, is
int main(int argc, char **argv)
The int in the front means the main function returns an int, which is the exit code of main. The perimeter passed in by the operating system argc and argv are related to command-line arguments. argc is an int indicating the number of arguments passed in to the program, including the name of the program. And argv is pointed to the individual arguments. You can use argv[index] to access them. There are several handy libraries for parsing arguments, such as getopt.