-2

If char* is a pointer (I find its size is always 4 bytes), how do I find its value (the address in hexa or decimal)? I tried &(*p) for char *p. It simply returned the initial string. If it is always 4 bytes, how is it that it can be initialized to long strings but point to the first character? In other words where is the string stored?

Is char* a weird pointer used for purposes other than what a pointer is intended to be?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 1
    What is `p`? What does "It simply returned the initial string" mean? [mcve] is much better than thousand words. – 273K Dec 17 '19 at 04:23
  • Hi @Ramesh, please consider looking for an answer to your question first before posting. For example: https://stackoverflow.com/questions/6655904/how-do-i-find-the-memory-address-of-a-string Thank you! – Kit Ostrihon Dec 17 '19 at 05:22
  • Does this answer your question? [How do I find the memory address of a string?](https://stackoverflow.com/questions/6655904/how-do-i-find-the-memory-address-of-a-string) – Kit Ostrihon Dec 17 '19 at 05:23

1 Answers1

0
// an initial pointer (usually its size is 32bit or 64bit, depending on CPU/OS).
// it's value is currently NULL (not pointing anywhere), 
// so we can't do very much with this right now. 
char* p = nullptr;

// for the sake of sanity, check the value (should be zero)
// we have to convert to intptr_t, otherwise we'd get the string
// value being printed out. 
std::cout << "p address = " << intptr_t(p) << std::endl << std::endl;

// lets allocate a few chars to play with
p = new char[10];

// copy in some text value 
std::strcpy(p, "Hello");

// and now if we print the address, the text string, 
// and the char we are pointing at
std::cout << "p address = " << intptr_t(p) << std::endl;
std::cout << "p string = " << p << std::endl;
std::cout << "p dereferenced = " << *p << std::endl << std::endl;

// for fun, lets increment the pointer by 1
++p;

// this should have made a couple of changes here
std::cout << "p address = " << intptr_t(p) << std::endl;
std::cout << "p string = " << p << std::endl;
std::cout << "p dereferenced = " << *p << std::endl << std::endl;

// decrement again (so we can delete the correct memory allocation!)
--p;

// now free the original allocation
delete [] p;

// if we print again, notice it still has the memory location?
std::cout << "p address = " << intptr_t(p) << std::endl;

// This would be bad to access (we've just deleted the memory)
// So as a precaution, set the pointer back to null
p = nullptr;

// should be back where we started
std::cout << "p address = " << intptr_t(p) << std::endl;
robthebloke
  • 9,331
  • 9
  • 12
  • Casting the pointers to `intptr_t` for the purpose of printing is wrong. To print `char*` pointers as pointers and not as strings, cast them to `void*` instead – Remy Lebeau Dec 17 '19 at 06:15