首页 > 解决方案 > 打印时将整数添加到 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%    

所以这就是我得到的。如果我增加数字,那么它只是将字符串切片。谁能解释这个输出以及为什么会发生在我身上?

标签: cstringprintf

解决方案


在 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()查找字符串连接。


推荐阅读