What are the arguments passed into the main method of a command-line program:
int main(int argc, const char * argv[])
what is the first int mean?
And what is the 2nd parameter, is that an array of chars?
How would one use these?
Also, what practical use is a command-line project type, other than using it to learn obj-c i.e. to practise.
int main(int argc, char *argv[]) The parameters argc , argument count, and argv , argument vector, respectively give the number and value of the program's command-line arguments. The names of argc and argv may be any valid identifier in C, but it is common convention to use these names.
argv(ARGument Vector) is array of character pointers listing all the arguments. If argc is greater than zero,the array elements from argv[0] to argv[argc-1] will contain pointers to strings. Argv[0] is the name of the program , After that till argv[argc-1] every element is command -line arguments.
As a concept, ARGV is a convention in programming that goes back (at least) to the C language. It refers to the “argument vector,” which is basically a variable that contains the arguments passed to a program through the command line.
The argv argument is a vector of C strings; its elements are the individual command line argument strings. The file name of the program being run is also included in the vector as the first element; the value of argc counts this element.
argc
means "argument count". It signifies how many arguments are being passed into the executable.
argv
means "argument values". It is a pointer to an array of characters. Or to think about it in another way, it is an array of C strings (since C strings are just arrays of characters).
So if you have a program "foo" and execute it like this:
foo -bar baz -theAnswer 42
Then in your main()
function, argc
will be 5, and argv
will be:
argv[0] = "/full/path/to/foo";
argv[1] = "-bar";
argv[2] = "baz";
argv[3] = "-theAnswer";
argv[4] = "42";
The parameters to main()
are a unix convention for accessing the arguments given on the command line when your program is executed. In a Cocoa app, you can access them the plain old C way, or you can use NSProcessInfo
's -arguments
method to get them in an NSArray
of NSString
objects, or use NSUserDefaults
to get them as values in a dictionary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With