2020年6月22日 星期一

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

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

接下來就想說
如果題目改為用在char上做string reverse……會怎樣呢?
像這樣↓
char *s = "123456";
void PointerReverseStr(char *s) {
  char *p_end = (char*)(& s + 1);
  char *p_beg = s;
  for (; p_beg < p_end; p_beg++, p_end--) {
    *p_end ^= *p_beg;
    *p_beg ^= *p_end;
    *p_end ^= *p_beg;
    printf("%c", *p_beg);
  }
  p_beg = s;
  for (; p_beg != '\0'; p_beg++) {
    printf("%c", *p_beg);
  }
}

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

所以改成以下這樣就可以正常跑了
char s[] = "123456";
void ReverseStr(char *s) {
 char* end = s + len(s) - 1;
 char* beg = s;
 for (; beg < end; beg++, end--) {
  *beg ^= *end;
  *end ^= *beg;
  *beg ^= *end;
 }
 beg = s;
 for (; *beg != '\0'; beg++) {
  printf("%c", *beg);
 }
}

沒有留言:

張貼留言

Eclipse 5.27.1 環境主題修改

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