VallyMan
VallyMan

Reputation: 135

C - Pointing to a character

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

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

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);

Demo.

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:

  • You need to dereference pointers *cPtr1 to print with %c
  • You need to use %p to print a pointer
  • When you print a pointer, you need to cast the argument to (void*).

Upvotes: 1

Petar Velev
Petar Velev

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

Related Questions