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
Related
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.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
If I understood correctly using of int main(int argc,char* argv[]) , whenever I've declared 4 integer argc must be 5. For example;
int main(int argc,char* argv[])
{
int portNb = 0;
int leftMotorHandle;
int rightMotorHandle;
int sensorHandle;
if (argc>=5)
{
portNb=atoi(argv[1]);
leftMotorHandle=atoi(argv[2]);
rightMotorHandle=atoi(argv[3]);
sensorHandle=atoi(argv[4]);
}
else
{
printf("Indicate following arguments: 'portNumber leftMotorHandle rightMotorHandle sensorHandle'!\n");
extApi_sleepMs(55000);
return 0;
}
But argc's value is 2 when i debugged the code. How can i be sure that argc has value of 5 ?
If I understood correctly using of 'int main(int argc,char* argv[])' , whenever I've declared 4 integer argc must be 5.
argc and argv have nothing to do with the number of variables you declare within your program. argc means the number of arguments you provide when you run it from the command line. argv is the array of char pointers that point to your arguments (including the name of your program itself).
Assume your program called proc. You would need to run it from command line as (or else you would need to find out from your IDE how to provide the command line arguments).
./proc 5 10 15 20
The numbers 5, 10, 15, 20 would be your argv[1] .. argv[4]
You should input not less than 4 arguments from the command line.
Separate the arguments by space.
Int argc is argument count, means how many arguments your are passing, including program name.
char pointer array represent arguments
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 does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I know that "Ali" is char array with 4 character: 'A' 'l' 'i' NULL
What i wanna know is the return value of it.
for example strcpy needs two pointer as input. why is the code below working:
char mstr[10]={};
strcpy(mstr,"Working...");
but this is not :
char *names[5]={"Ali","Reza","Hassan","Ahmad","Mohammad"};
"Ali" is a pointer to 'A' character or not?!
problem fixed!!! (i cant understand why?! i just add something to print them!) :
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main()
{
char mstr[10]={};
strcpy(mstr,"Working...");
char *names[5]={"Ali","Reza","Hassan","Ahmad","Mohammad"};
int i;
//print :
for(i=0;i<5;i++)
{
puts(names[i]);
}
getch();
return 0;
}
I think i find out what happened here. my second code is completely correct in C. I was compiling it as a c++ file (it was a cpp file)
By the way error was : [Error] invalid conversion from 'char' to 'const char*' [-fpermissive]
C++ has different rules and by default it defined 5 const char arrays not char arrays.
I think it was the answer.
In C, this declaration:
char *names[5]={"Ali","Reza","Hassan","Ahmad","Mohammad"};
is perfectly legal, but potentially dangerous. It defines names as an array of 5 char* pointers, each of which points to the first character of a string literal. The problem is that attempting to modify a string literal has undefined behavior (string literals aren't const for historical reasons). So this declaration allows you to do something like:
names[0][0] = 'E'; /* rename Ali to Eli? */
with no complaint from the compiler; it's likely to crash during execution. (A compiler is permitted, but not required, to warn about this.)
The above should be written as:
const char *names[5]={"Ali","Reza","Hassan","Ahmad","Mohammad"};
which makes names an array of 5 pointers to const (read-only) char.
As for why the code is not working for you, it's because you attempted to compile it as C++ (which you mentioned only in a commment). C++ is a different language than C, and has different rules. (In C++ the conversion is permitted but deprecated.) If you want to ask about C++, please post a new question with the C++ tag -- and be sure to clearly show the exact error message in the body of the question, not buried in a comment.
Study the following - perhaps it will help:
#include <stdio.h>
#include <strings.h>
int main(int argc, char **argv)
{
char mstr[11]; /* must be **11** elements in size to hold "Working..." */
char *names[5]={"Ali","Reza","Hassan","Ahmad","Mohammad"};
int i;
strcpy(mstr, "Working...");
printf("Print #1 - mstr='%s'\n", mstr);
for(i = 0 ; i < sizeof(names)/sizeof(names[0]) ; ++i)
printf("Print #2 - names[%d] = '%s'\n", i, names[i]);
}
Share and enjoy.
Strings in C are pointers to char (= char *). The value of "foo" is, as you said, a pointer. The reason your second example doesn't work is that char *names[5] is a pointer to char * (= char **). It's not a string, it's an array of strings, and since arrays are pointers, it's a pointer to a string. Since strings are arrays (= pointers) of characters, it's a pointer-to-a-pointer-to-char.
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.