Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is argv (argument vector) in C defined as a pointer and what is the need for defining its zeroth as the program name?

#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;
} 

Given above is a simple C program that outputs command line inputs. Here argc is the argument counter. argv is said to be an array that contains arguments. My question is: why does it define as a pointer to a character array instead of a normal array? Also what is the need for defining its zeroth element (argv[0]) as the name by which the program is invoked.

I am a beginner and please explain it high level perspective.

like image 264
user3298129 Avatar asked Dec 08 '25 22:12

user3298129


1 Answers

argv is defined as a pointer rather than as an array because there is no such thing as an array parameter in C.

You can define something that looks like an array parameter, but it's "adjusted" to array type at compile time; for example, these two declarations are exactly equivalent:

int foo(int param[]);
int foo(int param[42]); /* the 42 is quietly ignored */
int foo(int *param);    /* this is what the above two declarations really mean */

And the definition of main can be written either as:

int main(int argc, char *argv[]) { /* ... */ }

or as

int main(int argc, char **argv) { /* ... */ }

The two are exactly equivalent (and the second one, IMHO, more clearly expresses what's actually going on).

Array types are, in a sense, second-class types in C. Code that manipulates array almost always does so via pointers to the elements, performing pointer arithmetic to traverse the elements.

Section 6 of the comp.lang.c FAQ explains the often confusing relationship between arrays and pointers.

(And if you've been told that arrays are "really" pointers, they're not; arrays and pointers are distinct things.)

As for why argv[0] points to the program name, that's just because it's useful. Some programs print their names in error messages; others may change their behavior depending on the name by which they're invoked. Bundling the program name with the command-line arguments was a fairly arbitrary choice, but it's convenient and it works.

like image 100
Keith Thompson Avatar answered Dec 11 '25 13:12

Keith Thompson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!