c - 打印时将整数添加到 C-String
问题描述
int main(){
printf("hello world"+2);
}
test.c:32:25: warning: adding 'int' to a string does not append to the string
[-Wstring-plus-int]
printf("hello world"+2);
~~~~~~~~~~~~~^~
test.c:32:25: note: use array indexing to silence this warning
printf("hello world"+2);
^
& [ ]
1 warning generated.
alpha@Desktop % ./a.out
llo world%
所以这就是我得到的。如果我增加数字,那么它只是将字符串切片。谁能解释这个输出以及为什么会发生在我身上?
解决方案
在 C 和 C++ 语言中,使用双引号定义的每个字符串的类型char*
(指向 char)都是静态分配的 char 数组。当您调用printf()
此类字符串时,它会执行以下操作:
void printf(char* str) {
while(*str!= '\0') {
// write the current character to stdout
write(STDOUT_FILENO, str, sizeof(char));
str ++;
}
}
我不知道它是否真的是这样写的,实际上可能不是,功能是一样的。它遍历字符串,直到找到空终止符 ( '\0'
)。所有指针几乎等同于long
,当您向它们添加一个数字时,它会增加它们的基础值sizeof(type)
,其中 type 是指针指向的值的类型。因此,当您向“Hello World”添加一个数字时,会printf()
认为您的字符串从不同的内存地址开始并打印“llo World”。
如@Elliott Frisch 所述,如果要打印末尾附加值“2”的字符串,则可以使用print("Hello World%d", 2)
.
我建议在 C 中查看sprintf()
并strcat()
查找字符串连接。
推荐阅读
- excel - 如何删除参数不是可选错误
- python - Python打开.doc文件
- javascript - 有没有办法在 javascript 循环期间使用 .splice() 添加元素?
- java - Spring Batch中TaskExecutor实现并行处理
- r - 增长率估计包中getClass("nonlinear_fit")的作用是什么?
- javascript - 将数据从 JSON 文件传递到 html
- html - Powershell 无法填写 HTML 表单
- c# - Excel Interop 将工作表的视图样式设置为普通视图
- python - Odoo 12 邮件通知
- amazon-web-services - 如何将 AWS Kinesis Video Stream(帧)发送到 EC2 实例?