tags:

views:

70

answers:

1

Hello,

gcc 4.4.4 c89

I am just wondering why I am getting different memory address. When I print the address of animals in main I get the following:

animals [ rabbit ] : [ 0xbfab2e48 ]
animals [ rabbit ] : [ 0xbfab2e48 ]

However, when I print in the function, I get different memory locations. I think they should be the same.

ptr animals [ rabbit ] : [ 0xbfab2e08 ]
ptr animals [ rabbit ] : [ 0xbfab2e08 ]

Many thanks for any advice,

int main(void)
{
    char *animals[] = {"rabbit", "cat", "dog", "elephant", "racoon", NULL};
    char *countries[] = {"india", "amercia", "france", "spain", "canada", "mexico", NULL};
    char *cars[] = {"ford fista", "Masda 3", "honda city", "toyata cote", NULL};
    char **ptr_data[] = {animals, countries, cars, NULL};

    printf("animals [ %s ] : [ %p ]\n", *animals, (void*)animals);
    printf("animals [ %s ] : [ %p ]\n", animals[0], &animals[0]);

    print_data_ptr(ptr_data);

    return 0;
}

void print_data_ptr(char ***ptr)
{
    char **data_list = NULL;

    printf("ptr animals [ %s ] : [ %p ]\n", *ptr[0], (void*)&ptr[0]);
    printf("ptr animals [ %s ] : [ %p ]\n", **ptr, (void*)ptr);
}
+3  A: 

animals is an array of char * values, and ptr_data is an array of char ** values.

When you initialise ptr_data in this line:

char **ptr_data[] = {animals, countries, cars, NULL};

animals is evaluated as a pointer to its first element - so ptr_data[0] is the same as &animals[0] - the address of the first char * in animals. The same thing happens in your two printf() functions in main - animals and &animals[0] evaluate to the same thing, which is also the pointer value stored in ptr_data[0].

Within your function, ptr is a pointer to the first element of ptr_data in main - so ptr is equivalent to &ptr_data[0]. &ptr[0] is completely equivalent to ptr - so &ptr[0] shows you the address of ptr_data[0], not what is stored there. If you print ptr[0] instead, you will get the address of animals[0].

caf