what is an argument list in c? Please I need a very simple explanation that if possible I'll remember for life! also... show me one containing an array
1 Answer
Command line arguments are the values that follow the program name when you run a c program from a command line. Let's look at an example:
./myprogram red blue green
./myprogram
is the program name. "red", "blue" and "green" are three arguments.
When a c program executes, all of the arguments are stored in a special array called argv[].
The special variable "argc" contains the number of elements in the argv array, including the program name.
Remember that arrays start with element 0. The argv[] array will contain the arguments based on their position, plus one special entry. argv[0] will always contain the program name as it was called.
So, in this example, the vars are as follows:
argc = 4
argv[0] = "./myprogram"
argv[1] = "red"
argv[2] = "blue"
argv[3] = "green"
Here's a simple program to demonstrate the contents:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
printf("argc = %i\n",argc);
for (int i = 0; i < argc; i++ )
{
printf("argv[%i] = \"%s\"\n",i,argv[i]);
}
}
So that's the explanation of argc, argv[] and command line arguments.
If you're talking about passing arguments to a function call, that's an entirely different topic that's taught a couple weeks into the class. ;-)
If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)