Reputation: 825
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.
Upvotes: 0
Views: 129
Reputation: 455
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.
Upvotes: 0
Reputation: 9590
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.
Upvotes: 0
Reputation: 12806
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.
Upvotes: 0
Reputation: 11896
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.
Upvotes: 0
Reputation: 30001
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);
Upvotes: 2
Reputation: 5348
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.
Upvotes: 0