Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different output between argv and normal array of strings

For the program given below, why does the first printf print different values for argv and &argv? The second printf prints the same value for a and &a. What is the mechanism by which argument variables passed to the program are stored?

#include<stdio.h>
    int main(int argc, char * argv[]){
    char * a[10];  
    printf("%d %d\n\n",argv,&argv);
    printf("%d %d",a,&a);  
    return 0;  
}

What is the mechanism of storing command line arguments to an array of strings

like image 457
Duggs Avatar asked Aug 21 '13 07:08

Duggs


1 Answers

The problem is not about argv is special, but about function argument passing. Try this program:

#include<stdio.h>

void foo(int a[])
{
    int b[10];
    printf("foo :%p %p\n",a,&a);
    printf("foo :%p %p\n",b,&b);
}

int main(int argc, char* argv[])
{
    int a[10];
    printf("main:%p %p\n", a, &a);
    foo(a);
    return 0;
}

The output in my machine:

main:0x7fffb4ded680 0x7fffb4ded680
foo :0x7fffb4ded680 0x7fffb4ded628
foo :0x7fffb4ded630 0x7fffb4ded630

The first and third line is not surprising since for an array arr, arr and &arr have the same value. The second line needs to be explained.

As you can see, when a is passed in the function foo, the value of a is not changed, but the address &a is changed since C functions always pass arguments by value, there will be a local copy of the argument inside the function.

It's the same with argv since it's just an argument in the function main.


EDIT: For those who disagrees with me, my answer is not against the other answer. On the contrary, they complete each other. argv is a pointer exactly because it's an array that's passed as function argument, and it "decayed" into a pointer. Again, argv is not special, it acts no different than other arrays that are passed as function argument, that's the whole point of my example code.

like image 105
Yu Hao Avatar answered Sep 29 '22 07:09

Yu Hao