为什么你可以添加一个整数到字符串字面量? [英] Why can you add an integer to a string literal?
问题描述
我在搞乱,注意到一些奇怪的东西。你实际上可以做a+ 2
,程序编译正常,但不输出任何内容。但是a+ 32
说数组下标是数组边界
。
I was messing around and noticed something strange. You can actually do "a" + 2
and the program compiles fine, but doesn't output anything. However "a" + 32
says array subscript is above array bounds
.
推荐答案
a实际上是一个const char [],但它可以不转换为const char * 或到char * ,当你对指针做数学运算时,它像数组下标语法。所以你正在创建一个新的指针,在字符串中更远。有关指针算术的参考可能很有用。如果你得到一个char *引用的文字,它仍然是未定义的修改它(从经验,它可能会崩溃,如果在只读页面,或可能更改所有引用,它使用)。
"a" is actually a const char[], but it can be converted without a cast to a const char* or to a char* and when you do math on pointers it works like array subscript syntax. So you're creating a new pointer which is farther along in the string. This reference on pointer arithmetic might be useful. If you do get a char* reference to the literal, it still is undefined to modify it (from experience it might crash if in read-only page, or might change all references where it is used).
这篇关于为什么你可以添加一个整数到字符串字面量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!