gcc 将 char* 和 char 添加为原始指针 ("str" + 'c')
gcc 添加 char*(例如“STRING”)和 char(例如“C”)作为指针的原因是什么?
const char *ccc = "Test1";
const char t = 'T';
const char *res = ccc + t;
printf("%s, %p, %d, %p\n", res, ccc, t, res);
输出
, 0x8048d97, 84, 0x8048deb
我的意思是,你能指出文档、标准规格或文章吗?我可以控制或禁用此行为吗?
UPD:我为什么要问,令人意外的是,
CString() + 'c'
它就会起作用
(char*)CString() + (char)char_var
当编译器找不到合适的运算符 + 时, 。我想也许禁用自动串联并找到所有这些地方(在遗留代码中)。但大多数时候我只是想找到该行为的确切文档。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在
ccc + t
中,t
被视为整数。最终效果是res
指向ccc
加 84 个字节,其中 84 是'T'
的 ASCII 代码。值得指出的是,
ccc + t
纯粹对指针进行操作,并不触及实际的字符串。我这样说是为了防止"Test" + 'T'
可能将字符附加到字符串中 - 但事实并非如此。In
ccc + t
,t
is treated as an integer. The net effect is thatres
points toccc
plus 84 bytes, where 84 is the ASCII code of'T'
.It is worth pointing out that
ccc + t
operates purely on the pointers, and does not touch the actual string. I am saying this in case there's any expectation that"Test" + 'T'
might append the character to the string -- it does not.这称为指针算术。例如,
ptr + x
相当于&ptr[x]
。It's called pointer arithmetic. For example
ptr + x
is equivalent to&ptr[x]
.C 没有字符串。 C 有数组和指针。
您应该将“字符串常量”
“Test1”
视为数组初始值设定项的语法糖{ 'T', 'e', 's', ' t', '1', 0x00 }
。C 甚至没有字符。 C 有小整数(通常是八位)。
您应该将“字符常量”
'T'
视为数字常量0x54
(假设为 ASCII)的语法糖。因此,当您编写时,
您将向指针添加一个小的正整数。不多也不少。
我会就如何做你想做的事情提供建议,但这会很乏味、冗长,而且会分散注意力。如今,C++ 有一个不错的字符串类,您可能会更高兴学习它。
C does not have strings. C has arrays and pointers.
You should think of the "string constant"
"Test1"
as syntactic sugar for the array initializer{ 'T', 'e', 's', 't', '1', 0x00 }
.C does not even have characters. C has small (eight-bit, usually) integers.
You should think of the "character constant"
'T'
as syntactic sugar for the numeric constant0x54
(assuming ASCII).So when you write
you're adding a small positive integer to a pointer. No more, no less.
I would offer advice on how to do the thing you wanted to do, but it would be tedious and verbose and distract from the point. C++ has a decent string class these days, you will probably be happier just learning that.