0

I'm a bit confused about the result of this code :

#include <stdio.h>
#include <stdlib.h>

int char_address(char *myChar)
{
        printf("IN FUNCTION ADRESS = %p\n", &myChar);
        return 0;
}

int main(int argc, char **argv)
{
        char *string;

        string = (char *)malloc(32 * sizeof(char));

        printf("IN MAIN ADDRESS = %p\n", &string);
        char_address(string);
        return 0;
}

The output is :

IN MAIN ADDRESS = 0x7fff6da87b90
IN FUNCTION ADRESS = 0x7fff6da87b78

I was expecting the same address?

Thanks for helping to understand what's going on.

6 Answers 6

2

You are printing the pointer to the address of the actual pointers. Remove the & in your printf call.

printf("IN MAIN ADDRESS = %p\n", string);

and

printf("IN FUNCTION ADRESS = %p\n", myChar);
2
  • Thanks for this answer, all others answers are fine.
    – funnyCoder
    Dec 4, 2011 at 3:00
  • When you print a pointer value using "%p", you should cast it to void* if it's not already of that type. char* is ok, but IMHO it's better to be consistent. Dec 4, 2011 at 3:24
0

No, because you print the address of the pointer, not the pointer itself. If you change

printf("IN MAIN ADDRESS = %p\n", &string);

to

printf("IN MAIN ADDRESS = %p\n", string);

and

printf("IN FUNCTION ADRESS = %p\n", &myChar);

to

printf("IN FUNCTION ADRESS = %p\n", myChar);

the values will be the same.

0

To get the same address, you need to do printf("IN FUNCTION ADRESS = %x\n", myChar);. When you do &myChar, you get the address on the stack where the pointer lives.

0

There is an error in your function, it should be:

printf("IN FUNCTION ADRESS = %p\n", myChar);

Because the function accepts a pointer as the argument, so the value of that variable is the address you are looking for. By using &, you are actually getting the memory address of the pointer variable itself, rather than the address of what it is pointing to.

0

The ans is you are printing wrong pointers.

IN MAIN ADDRESS &string = 0x7fff60f312b0
IN MAIN ADDRESS string = 0x1014009a0
IN FUNCTION ADRESS &mychar= 0x7fff60f31298
IN FUNCTION ADRESS mychar= 0x1014009a0

See when you passing the pointer to function then copy of pointer is created. So new pointer's address is different. But both the pointers point to same address.

0

When you use the ampersand you're getting the address of the pointer variable, not the pointer value. That is, the address of 'string' (which would be on the stack), and the address of myChar (which is also on the stack) aren't the same.

I think you meant to do this without the ampersands before string and myChar. Then they'd print the values contained by string and myChar which should be the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.