Monday, May 24, 2010

Question about command line arguments for C/C++, argv?

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





ok in this case,,, argv[] is supposed to be an array of pointers pointing to input





why is it possible to say


puts(argv[1])? //putstring





if argv is an array of pointers, wouldn't that print a memory address? but why then does it actually print the actual argument passed.





Don't we need to dereference it first... like


puts(*argv[1])?





I would greatly appreciate your help. Thanks!

Question about command line arguments for C/C++, argv?
You are correct in your understanding that argv is an array of pointers. So argv[1] is just a pointer. There are two critical insights to understanding this.





Critical insight #1: In C and C++, a pointer can be used as an array. So if you have a char*, that can point to either a single character, or to an array. Because of this, if you have "char *a;", the statements "*a" and "a[0]" are exactly the same thing. (Of course, you can't say "a[1]" if a is just a pointer to a single character. The results will be undefined.)





Critical insight #2: In C, strings (referred to in C++ as "C-style strings" to distinguish them from C++'s std::string class) are just arrays of characters. And when you pass a string (that is, a "char*") to puts(), the string itself is printed out, not its address.





Thus, if you say


char *foo = "bar"; puts(foo);


you will see "bar" as the program's output. Likewise, if you say


char *foo = argv[1]; puts(foo);


you will see the second argument to the program. (Why the second? Because argv[0] is the first argument.)





Something important to remember is that puts() will only print out strings. If you say "puts(3)" or "puts(argv)" your code won't compile. puts() always does the dereferencing on its own.
Reply:argv[1] stores address but *argv[1] gives the value stored at argv[1] address
Reply:It's not "an array of pointers pointing to input". It's actually a vector (or array) of char* (or strings) so each element in the vector is a null terminated string.





argv[0] is the program name


argv[1] is the first parameter passed to the program (separated by spaces)


and so on.





Hope that helps!!

surveys

No comments:

Post a Comment