2020年6月22日 星期一

使用char*做string reverse時的一些小事

在寫string reverse時發生的一些小事
之前在寫面試試題時遇過以下這個問題
  1. int main() {
  2. int a[5] = { 1, 2, 3, 4, 5 };
  3. int *ptr = (int *)(&a + 1);
  4. printf("%d,%d\n", *(a + 1), *(ptr - 1));
  5. }

接下來就想說
如果題目改為用在char上做string reverse……會怎樣呢?
像這樣↓
  1. char *s = "123456";
  2. void PointerReverseStr(char *s) {
  3. char *p_end = (char*)(& s + 1);
  4. char *p_beg = s;
  5. for (; p_beg < p_end; p_beg++, p_end--) {
  6. *p_end ^= *p_beg;
  7. *p_beg ^= *p_end;
  8. *p_end ^= *p_beg;
  9. printf("%c", *p_beg);
  10. }
  11. p_beg = s;
  12. for (; p_beg != '\0'; p_beg++) {
  13. printf("%c", *p_beg);
  14. }
  15. }

結論是炸開~
完全錯的一蹋糊塗,現在回頭看真的不知道從何吐槽而起
首先
  1. char *p_end = (char*)(&s + 1);
  2. for (; p_end != p_beg; p_end--) {
  3. printf("%c", *p_end);
  4. }
  5. /*他指向的不是一個陣列,所以用&s+1跟前面的用法完全不同
  6. 可以看到印出來一些奇怪的東西,如下
  7. ps:如果有高人知道是為什麼,請指正*/
再來
  1. char *s="123456";
這個東西本來就是不能修改的
因為char*="12345"跟const char*="12345"是一樣的
無法更改裡面的值
如果要能修改要改為
  1. char s[]="123456";
參考:https://stackoverflow.com/questions/1011455/is-it-possible-to-modify-a-string-of-char-in-c

所以改成以下這樣就可以正常跑了
  1. char s[] = "123456";
  2. void ReverseStr(char *s) {
  3. char* end = s + len(s) - 1;
  4. char* beg = s;
  5. for (; beg < end; beg++, end--) {
  6. *beg ^= *end;
  7. *end ^= *beg;
  8. *beg ^= *end;
  9. }
  10. beg = s;
  11. for (; *beg != '\0'; beg++) {
  12. printf("%c", *beg);
  13. }
  14. }

沒有留言:

張貼留言

Eclipse 5.27.1 環境主題修改

Eclipse 環境設定 1. 主題 Window->Preferences->General->Appearance->Theme->Dark 2. 文字大小 Window->Preferences->General-...