Search code examples
carrayspointersmemory-addressargv

av[1] and av[1][0] Not the same address?


What's up ? I can't understand this issue... I know that the first element of an array stock the address of the entire array. But in this situation i can't figure it out.

#include <stdio.h>

int main(int ac, char **av)
{
    printf("&av[1]= %p\n", &av[1]);
    printf("&av[1][0]= %p\n", &av[1][0]);

    return(0);
}

Input

./a.out "Hello"

Output

&av[1]= 0x7ffee0ffe4f0
&av[1][0]= 0x7ffee0ffe778

Solution

  • If somebody told you that char **av declares a two-dimensional array, they did you a disservice. In char **av, av is a pointer to a char *, possibly the first char * of several. So av[1] is a char *—it is a pointer to a char, and &av[1] is the address of that pointer.

    av[1][0] is the char that av[1] points to, and &av[1][0] is the address of that char.

    The pointer to the char and the char are of course not in the same place, so &av[1] and &av[1][0] are different.

    In contrast, if you had an array, such as char av[3][4], then av is an array of 3 arrays of 4 char. In that case, av[1] is an array of 4 char, and &av[1] would be the address of (the start of) that array. &av[1][0] would be the address of the first char in that array. Since the char is at the beginning of the array, the address of the array and the address of the char are the same.

    (However, they are not necessarily represented the same way in a C implementation, and printing them with %p can show different results even though they refer to the same place in memory.)