2017-10-20 57 views
-2


我想輸出一個二進制格式的字符串,但在第一次執行*s << = 1;我得到一個段錯誤。
錯誤在哪裏?左算術移位的分段錯誤

#include <stdio.h> 
#include <uchar.h> 
#include <locale.h> 
#include <string.h> 

int main() { 
    setlocale(LC_CTYPE, ""); 
    char *s = u8"\uD798"; 
    int c = (sizeof *s) * strlen(s); 
    for(int i = 0; i < 8 * c; i++) { 
     putchar(*s & 0x80 ? '1' : '0'); 
       fflush(stdout); 
     if((i + 1) % 8 == 0 && i != 0) { 
      putchar('\n'); 
      s++; 
     } 
     *s <<= 1; //segfault here 
    } 
    printf("\n%s - %i\n", u8"\uD798", c); 
    return 0; 
} 
+2

嘗試'char s [] = u8「\ uD798」;'將該字符串寫入可讀寫內存 – Ctx

+0

文字不可修改。 – CiaPan

+0

'const char * s = u8「\ uD798」;'將允許編譯器捕獲錯誤而不是運行時。 – Clifford

回答

2

指針s指向字符文字,它存儲在只讀存儲器中。你不能修改它。