Reputation: 135
I am trying to have a pointer point to a character, and then another pointer pointing to the first pointer, making both of them have the same values stored.
char ch = 'A';
char *cPtr1, *cPtr2;
cPtr1 = &ch;
cPtr2 = cPtr1;
printf("cPtr1 Stored:%c Point:%x Memory:%x\n", cPtr1, *cPtr1, &cPtr1);
printf("cPtr2 Stored:%c Point:%x Memory:%x\n", cPtr2, *cPtr2, &cPtr2);
The issue is that everytime I run it, it stores a different character and always points to '41'. What am i doing wrong?
Upvotes: 0
Views: 76
Reputation: 726629
You have a little mix-up with what to pass to printf
. Here is what you are looking for:
printf("cPtr1 Stored:'%c' Point:%p Memory:%p\n", *cPtr1, (void*)cPtr1, (void*)&cPtr1);
printf("cPtr2 Stored:'%c' Point:%p Memory:%p\n", *cPtr2, (void*)cPtr2, (void*)&cPtr2);
As you can see, both cPtr1
and cPtr2
are pointing to the same character. Moreover, the two pointers are the same. Pointers themselves, however, occupy separate locations in memory.
Explanation of changes:
*cPtr1
to print with %c
%p
to print a pointer(void*)
.Upvotes: 1
Reputation: 2355
The problem is that you're printing the address after "Stored:"
ch = 'A';
cPtr* = &ch;
printf("%x",cPtr); // Printing the pointer value(the address of the stored char).
printf("%c",*cPtr); // Printing the value which the pointer points to(dereferencing).
printf("%x",&cPtr); // Printing the address of the pointer itself.
Upvotes: 0