Strings: Using Pointers

bumsfeld 1 Tallied Votes 118 Views Share

My first experience with pointers. Learned how to spell a string foreward and backward using pointers. I hope you can learn too!

// Spell a string forward and backward using a pointer in C

#include <stdio.h>

#define EOS  0   // End of string marker

int main()
{
  char *ptr1, *ptr2;

  // ptr2 is used to hold starting position of string
  ptr1 = ptr2 = "The red cow jumped over the blue moon";
  printf("\n %c %s %c\n (This string has %d characters)",16,ptr1,17,strlen(ptr1));
  printf("\n\n ptr1 starts at address %u pointing to %c = %d\n\n",ptr1,*ptr1,*ptr1);
  printf("Spell forward %c ",16);

  // Spell it till EOS is reached
  while( *ptr1 != EOS )
  {
    printf("%c",*ptr1++);
  }
  printf("\n\n ptr1 is now at address %u pointing to %c = %d",ptr1,*ptr1,*ptr1);
  printf("\n (a value of  0  indicates the end of string marker)\n\n");
  printf("Spell backward %c ",16);

  // Spell backwards to address held in ptr2
  while( --ptr1 >= ptr2 )
  {
    printf("%c",*ptr1);
  }
  ptr1++;

  printf("\n\n ptr1 is now at address %u pointing to %c = %d\n",ptr1,*ptr1,*ptr1);

  getchar();   /* wait for key */
  return 0;
}