Strings: Using Pointers

bumsfeld bumsfeld is offline Offline Aug 1st, 2005, 1:29 pm |
0
My first experience with pointers. Learned how to spell a string foreward and backward using pointers. I hope you can learn too!
Quick reply to this message  
C Syntax
  1. // Spell a string forward and backward using a pointer in C
  2.  
  3. #include <stdio.h>
  4.  
  5. #define EOS 0 // End of string marker
  6.  
  7. int main()
  8. {
  9. char *ptr1, *ptr2;
  10.  
  11. // ptr2 is used to hold starting position of string
  12. ptr1 = ptr2 = "The red cow jumped over the blue moon";
  13. printf("\n %c %s %c\n (This string has %d characters)",16,ptr1,17,strlen(ptr1));
  14. printf("\n\n ptr1 starts at address %u pointing to %c = %d\n\n",ptr1,*ptr1,*ptr1);
  15. printf("Spell forward %c ",16);
  16.  
  17. // Spell it till EOS is reached
  18. while( *ptr1 != EOS )
  19. {
  20. printf("%c",*ptr1++);
  21. }
  22. printf("\n\n ptr1 is now at address %u pointing to %c = %d",ptr1,*ptr1,*ptr1);
  23. printf("\n (a value of 0 indicates the end of string marker)\n\n");
  24. printf("Spell backward %c ",16);
  25.  
  26. // Spell backwards to address held in ptr2
  27. while( --ptr1 >= ptr2 )
  28. {
  29. printf("%c",*ptr1);
  30. }
  31. ptr1++;
  32.  
  33. printf("\n\n ptr1 is now at address %u pointing to %c = %d\n",ptr1,*ptr1,*ptr1);
  34.  
  35. getchar(); /* wait for key */
  36. return 0;
  37. }

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC