C语言 string + int 在 C 中的表现是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19265370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:40:36  来源:igfitidea点击:

What does string + int perform in C?

cstringpointers

提问by Abhishek

I can't figure out this expression:

我无法弄清楚这个表达:

str + n

where char str[STRING_LENGTH]and int n.

哪里char str[STRING_LENGTH]int n

I have worked a lot in Java and was assuming till now that it's concatenation of string and integer, which I doubt now.

我在 Java 中做了很多工作,并且一直假设它是字符串和整数的连接,我现在对此表示怀疑。

What does it mean?

这是什么意思?

回答by Yu Hao

It's pointer arithmetic. For instance:

这是指针算法。例如:

char* str = "hello";
printf("%s\n", str + 2);

Output: llo. Because str + 2point to 2 elements after str, thus the first l.

输出:llo。因为str + 2指向 2 个元素之后str,因此是第一个l

回答by Bathsheba

strcan be regarded as pointing to the memory address associated with a character sequence of length STRING_LENGTH. As such, c pointer arithmeticis being exploited in your statement str + n. What is is doing is pointing to the memory address of the nthcharacter in the character sequence.

str可以看作是指向一个长度为STRING_LENGTH的字符序列关联的内存地址。因此,您的语句中正在利用c 指针算法str + n。做的是指向字符序列中n第th个字符的内存地址。

回答by Bijaya Bidari

Yes ans of @Yu Hao and @Bathsheba are correct.
But if you want to do the concatenation, you can go as following code snippet.

@Yu Hao 和 @Bathsheba 的回答是正确的。
但是如果你想进行连接,你可以按照以下代码片段进行操作。

char string[]="hello";
int number=4;
char cated_string[SIZE_CATED_STRING];
sprintf(cated_string,"%s%d",string,number);
printf("%s",cated_string);

Happy Coding.

快乐编码。