左算术移位的分段错误
问题描述:
我想输出一个二进制格式的字符串,但在第一次执行*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;
}
答
指针s
指向字符文字,它存储在只读存储器中。你不能修改它。
尝试'char s [] = u8“\ uD798”;'将该字符串写入可读写内存 – Ctx
文字不可修改。 – CiaPan
'const char * s = u8“\ uD798”;'将允许编译器捕获错误而不是运行时。 – Clifford