C pointers

C pointers

February 12, 2021
C, programming

tags
Programming Computer Science

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.

Address0x10x20x30x40x50x60x70x80x90xA
Value0x6seds\0
Variable namehostnamehostnamehostname + 1hostname + 2hostname + 3hostname +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 '0x7ffee8b04188', *hostname is 's' and hostname is 'seds'
hostname address is '0x1070fee42' and hostname[0] address is 0x1070fee42

hostname + 1 address is '0x1070fee43' and hostname[1] address is 0x1070fee43
hostname + 2 address is '0x1070fee44' and hostname[2] address is 0x1070fee44
hostname + 3 address is '0x1070fee45' and hostname[3] address is 0x1070fee45
hostname + 4 address is '0x1070fee46' and hostname[3] address is 0x1070fee46
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 0x109753f5a
hostname is 'e', at address 0x109753f5b
hostname is 'd', at address 0x109753f5c
hostname is 's', at address 0x109753f5d
Hostname is out of bound: '', at address 0x109753f5e


No notes link to this note