944,106 Members | Top Members by Rank

Ad:
  • C Code Snippet
  • Views: 4232
  • C RSS
0

Strings: Using Pointers

by on Aug 1st, 2005
My first experience with pointers. Learned how to spell a string foreward and backward using pointers. I hope you can learn too!
C Code Snippet (Toggle Plain Text)
  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:
Previous Thread in C Forum Timeline: remote system
Next Thread in C Forum Timeline: Continued Fraction Expansion





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC