...you should allocate certain memory for that pointer ...
No, you seems to misunderstand about pointers...
Pointer is the type which hold some type's address. Look at this example.
int a = 1;
int *p = &a;
The type of a
is int
, which contains integer.
The type of p
is int *
, which contains address of integer variables.
Let's suppose memory like this:
--------------------------------------
variables: | a | p |
--------------------------------------
address : | 0x12341234 | 0x12341238 |
--------------------------------------
the &
operator gets the address of operand. So, &a
is equal to 0x12341234
.
So the variables are initialized like this:
--------------------------------------
variables: | a | p |
--------------------------------------
address : | 0x12341234 | 0x12341238 |
--------------------------------------
value : | 1 | 0x12341234 |
--------------------------------------
Now, look this code, *p
. the *
operator, dereference operator, gets the value of the variables which the pointer is pointing. In this case, p
contains 0x12341234
- What variables is in 0x12341234
? the a
! So *p
is equal to 1
, which a
contains.
Now look this example:
#include <stdlib.h>
char c1 = '1';
int main()
{
char c2 = '2';
char *p1 = &c1;
char *p2 = &c2;
char ar[13] = "hello world!"; /* don't forget '\0' : 12 + 1. */
char *p3 = &ar[0];
const char *p4 = "hello world!"; /* notice the type, `const char *` */
char *p5 = malloc(13 * sizeof(char));
}
c1
is global variables, so compiler place it on the data section of program directly. c2
is local variables of main
, so it is placed on stack by main
. Anyway, they're placed on memory. And p1
and p2
contains their address, so *p1
is '1'
(c1
) and *p2
is '2'
(c2
).
ar
is 13-length array of char
. It is placed on memory like this:
------------------------------------------------------
|'h'|'e'|'l'|'l'|'o'|' '|'w'|'o'|'r'|'l'|'d'|'!'|'\0'|
------------------------------------------------------
And &ar[0]
is the address of the first element of ar
, so p3
contains the address of 'h'
.
Now look at p4
. It's initialized by "hello world!"
. Your question is where it is allocated - it's just (string) constant, like 1234
, 2.71
or 'a'
. Constant is placed on the program directly, by compiler. Like c1
, the string constant is placed on the rodata section of program directly. Contrast to data section, rodata section is read-only (Read Only DATA) because string constant is constant. (As you know, constant is read-only.) So the type of p4
is const char *
.
p5
is initialized by return value of malloc
, that is from dynamic allocation. In this case, malloc
allocates the memory somewhere, and p5
is initialied by this.