ptrstr.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435
  1. // ptrstr.cpp -- using pointers to strings
  2. #include <iostream>
  3. #include <cstring> // declare strlen(), strcpy()
  4. int main()
  5. {
  6. using namespace std;
  7. char animal[20] = "bear"; // animal holds bear
  8. const char * bird = "wren"; // bird holds address of string
  9. char * ps; // uninitialized
  10. cout << animal << " and "; // display bear
  11. cout << bird << "\n"; // display wren
  12. // cout << ps << "\n"; //may display garbage, may cause a crash
  13. cout << "Enter a kind of animal: ";
  14. cin >> animal; // ok if input < 20 chars
  15. // cin >> ps; Too horrible a blunder to try; ps doesn't
  16. // point to allocated space
  17. ps = animal; // set ps to point to string
  18. cout << ps << "!\n"; // ok, same as using animal
  19. cout << "Before using strcpy():\n";
  20. cout << animal << " at " << (int *) animal << endl;
  21. cout << ps << " at " << (int *) ps << endl;
  22. ps = new char[strlen(animal) + 1]; // get new storage
  23. strcpy(ps, animal); // copy string to new storage
  24. cout << "After using strcpy():\n";
  25. cout << animal << " at " << (int *) animal << endl;
  26. cout << ps << " at " << (int *) ps << endl;
  27. delete [] ps;
  28. // cin.get();
  29. // cin.get();
  30. return 0;
  31. }