C pointers
February 12, 2021 |
c,
programming
- Related pages
For understanding how pointers work, consider the following simplified memory
layout. the memory address starts in 0x1
and goes up to address 0xA
. The
value row holds the current data stored in that memory cell. Address 0x1
holds
a pointer to address 0x6
, which in turn 0x6
holds the value s
.
Address | 0x1 | 0x2 | 0x3 | 0x4 | 0x5 | 0x6 | 0x7 | 0x8 | 0x9 | 0xA |
---|---|---|---|---|---|---|---|---|---|---|
Value | 0x6 | s | e | d | s | \0 | ||||
Variable name | hostname | hostname | hostname + 1 | hostname + 2 | hostname + 3 | hostname +4 |
.. which we can translate to:
int main() {
char *hostname = "seds"; /* hostname points to 0x6 */
printf("&hostname is '%p', *hostname is '%c' and hostname is '%s'\n",
&hostname, *hostname, hostname);
printf("hostname address is '%p' and hostname[0] address is %p\n\n", hostname,
&hostname[0]);
printf("hostname + 1 address is '%p' and hostname[1] address is %p\n",
hostname + 1, &hostname[1]);
printf("hostname + 2 address is '%p' and hostname[2] address is %p\n",
hostname + 2, &hostname[2]);
printf("hostname + 3 address is '%p' and hostname[3] address is %p\n",
hostname + 3, &hostname[3]);
printf("hostname + 4 address is '%p' and hostname[3] address is %p\n",
hostname + 4, &hostname[4]);
}
&hostname is '0x16b666398', *hostname is 's' and hostname is 'seds'
hostname address is '0x10479be3c' and hostname[0] address is 0x10479be3c
hostname + 1 address is '0x10479be3d' and hostname[1] address is 0x10479be3d
hostname + 2 address is '0x10479be3e' and hostname[2] address is 0x10479be3e
hostname + 3 address is '0x10479be3f' and hostname[3] address is 0x10479be3f
hostname + 4 address is '0x10479be40' and hostname[3] address is 0x10479be40
int main() {
char *hostname = "seds"; /* hostname points to 0x6 */
printf("Hostname is '%s'\n", hostname);
printf("Hostname first char '%c'\n", *hostname);
printf("Hostname second char '%c'\n", *(hostname + 1));
printf("Hostname third char '%c'\n", *(hostname + 2));
printf("Hostname fourth char '%c'\n", *(hostname + 3));
printf("Hostname last char '%d'\n", *(hostname + 4));
printf("Out of bound (garbage) '%c'\n", *(hostname + 5));
}
Hostname is 'seds'
Hostname first char 's'
Hostname second char 'e'
Hostname third char 'd'
Hostname fourth char 's'
Hostname last char '0'
Out of bound (garbage) 'H'
int main() {
char *hostname = "seds"; /* hostname points to 0x6 */
while (*hostname) {
printf("hostname is '%c', at address %p \n", *hostname, hostname);
hostname++;
}
printf("Hostname is out of bound: '%s', at address %p\n", hostname, hostname);
}
hostname is 's', at address 0x104b87f50
hostname is 'e', at address 0x104b87f51
hostname is 'd', at address 0x104b87f52
hostname is 's', at address 0x104b87f53
Hostname is out of bound: '', at address 0x104b87f54