Richie
Richie

Reputation: 19

Memory address of strings declared using a char pointer

I read that when you declare strings using a pointer, the pointer contains the memory address of the string literal. Therefore I expected to get the memory address from this code but rather I got some random numbers. Please help me understand why it didn't work.

int main()
{
    char *hi = "Greeting!";
    printf("%p",hi);
    return(0);
}

If the pointer hi contains the memory address of the string literal, then why did it not display the memory address?

Upvotes: 0

Views: 816

Answers (3)

François Andrieux
François Andrieux

Reputation: 29023

A pointer could be represented in several ways. The format string "%p" "writes an implementation defined character sequence defining a pointer" link. In most cases, it's the pointed object's address interpreted as an appropriately sized unsigned integer, which looks like "a bunch of random number".

A user readable pointer representation is generally only useful for debugging. It allows you to compare two different representations (are the pointers the same?) and, in some cases, the relative order and distance between pointers (which pointer comes "first", and how far apart are they?). Interpreting pointers as integers works well in this optic.

It would be helpful to us if you could clarify what output you expected. Perhaps you expected pointers to be zero-based?

Note that, while some compilers might accept your example, it would be wiser to use const char *. Using a char * would allow you to try to modify your string literal, which is undefined behavior.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234665

It did work. It's just that you can consider the address as being arbitrarily chosen by the C runtime. hi is a pointer set to the address of the capital G in your string. You own all the memory from hi up to and including the nul-terminator at the end of that string.

Also, use const char *hi = "Greeting!"; rather than char *: the memory starting at hi is read-only. Don't try to modify the string: the behaviour on attempting to do that is undefined.

Upvotes: 1

EFrank
EFrank

Reputation: 1900

The "random numbers" you got are the Memory addresses. They are not constant, since on each execution of your program, other Memory addresses are used.

Upvotes: 0

Related Questions