Skip to main content
\(\newcommand{\doubler}[1]{2#1} \newcommand{\binary}{\mathtt} \newcommand{\hex}{\mathtt} \newcommand{\octal}{\mathtt} \newcommand{\prog}{\mathtt} \newcommand{\lt}{<} \newcommand{\gt}{>} \newcommand{\amp}{&} \)

Section2.14Programming Exercise

1

Write a program in C that creates a display similar to Figure 2.13.2.

Hint

The C statement char *stringPtr = "Hello world.\n"; will give you some characters to display and the pointer variable, stringPtr, to access them. The printf formatting codes are %p for the pointer variable and 0x%02x to display the byte at each address in hexadecimal. If pointer variables are new to you, use *stringPtr to access the memory pointed to by the variable; * is called the dereferencing operator.

Solution
/* stringInHex.c
 * displays each character in "Hello world" in hex
 * and the address where it is stored.
 *
 * 2017-09-29: Bob Plantz
 */

#include <stdio.h>

int main(void)
{
  char *stringPtr = "Hello world.\n";

  while (*stringPtr != '\0')
  {
    printf("%p:  ", stringPtr);
    printf("0x%02x\n", *stringPtr);
    stringPtr++;
  }
  printf("%p:  ", stringPtr);
  printf("0x%02x\n", *stringPtr);

  return 0;
}