About Lesson
When running a C program, there is usually a way to pass command-line arguments or parameters to the program. When main function is invoked, it is called with two arguments.
- argument count: The first argument is the number if command-line arguments the program was invoked with.
- argument vector: The second argument is a pointer to an array of character strings that contain the actual arguments passed at command-line.
Let’s look at the following program that implements the unix command-line utility echo, which simply prints its argument to the screen. Example:
echo Hello World!
prints
Hello World!
Here is the implementation:
/* echo.c */
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
for (i = 1; i < argc; i++)
printf("%s%s", argv[i], i != argc - 1 ? " " : "");
printf("\n");
return 0;
}
To run this code:
cc echo.c ./a.out Hello World!
Output:
Hello World!