[英]Initialize and print const char pointer
I got this code:我得到了这段代码:
const char *newLine = "\n";
printf('Content: %c\n', *newLine);
What happens now is a memory error.现在发生的是 memory 错误。
Why is that happening?为什么会这样?
The code crashes with a memory error (segmentation fault) because printf
expects a null-terminated string as the first argument (ie a valid address pointing to some characters ending in a zero byte), but you are passing an (effectively random) integer to it which is not a valid address (unless you are very, very lucky:-).代码崩溃并出现 memory 错误(分段错误),因为
printf
需要一个以空字符结尾的字符串作为第一个参数(即指向某些以零字节结尾的字符的有效地址),但您正在将(有效随机的)integer 传递给它不是一个有效的地址(除非你非常非常幸运:-)。
As people commented, use double quotes to pass an actual string allocated by the compiler somewhere:正如人们评论的那样,使用双引号将编译器分配的实际字符串传递到某处:
const char *newLine = "\n";
printf("Content: %c\n", *newLine);
Try this code试试这个代码
const char* newLine = "new Line";
printf("Content: %s\n", newLine);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.