When you put literal strings such as "Hello" in your program, the compiler creates an array of characters in the data area of the program (called the Data Segment).
When you assign:
p="Hello";
the compiler takes the address of the string literal in the data segment and puts it in the pointer variable p.
Notice that string literals are different to numeric literals. The type of a string literal is const char[]
- which you can assign to a char* pointer. An integer literal is just type int
.
Also note that a numeric literal does not need to be stored in the data segment - in most cases such literals are placed directly in the machine code instructions. Thus there is no address which you could point p towards.
If you tried to do this (as per your comment):
int *p;
*p = 5;
what you are actually saying is that you want to store the number 5 into the location pointed to by p (which would be undefined in this case, since we never set p to anything). You would probably get a segfault.
If you tried to do this:
int *p;
p = 5;
what you would be telling the compiler to do is to convert the value 5 into a pointer to an integer and store that in p, with the result that the pointer p now points at address 5. And you would probably get a warning like this:
t.c:7: warning: assignment makes pointer from integer without a cast
In other words, you are trying to convert an integer to a pointer - probably not what you thought you were trying to do.