[cc150] 1.2

1668 ワード

1.2 Write code to reverse a C-Style String.

  
  
  
  
  1. class Solution { 
  2. public
  3.     void reverse(char *str){ 
  4.         if (!*str) return
  5.         char *p = str, *q = str; 
  6.         while (*q) q++; 
  7.         q--; 
  8.         char tmp; 
  9.         while (p < q) { 
  10.             tmp = *p; 
  11.             *p++ = *q; 
  12.             *q-- = tmp; 
  13.         } 
  14.     } 
  15. }; 

このテーマにも何か特別なことがありますが、注意しなければならないのは文字列の定義方法です.
char*str="hello"はコードセグメントに置かれており、char str[10]="hello"はスタックに置かれているので、任意に使用できますが、アドレスが境界を越えないように注意してくださいね