C、指针、字符串
main()
{
char *x="girl";
int n,i;
n=strlen(x);
*x=x[n];
for(i=0;i<n;i++)
{
printf("%s \n",x);
x++;
}
}
输出是什么?
请解释输出......................
o/p 是:
irl
rl
l
main()
{
char *x="girl";
int n,i;
n=strlen(x);
*x=x[n];
for(i=0;i<n;i++)
{
printf("%s \n",x);
x++;
}
}
What is the output?
Please explain the output.......................
o/p is :
irl
rl
l
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
输出是未定义的行为。您修改了字符串文字。
The output is undefined behaviour. You modified a string literal.
正如其他人指出的那样,编写的程序具有未定义的行为。
如果你做了一个小改动:
那么我相信这是合法的,并且可以解释。 (编辑:实际上它仍然存在问题。它是
int main()
,你应该在最后return 0;
。你还需要#include
因为您使用的是strlen
,#include
因为您使用的是printf
>.)该行将
x[0]
(即*x
)设置为x[4]
(恰好是字符串终止符 <代码>'\0')。因此,要打印的第一个字符串是空字符串,因为第一个字符是字符串终止符。然后我们循环遍历字符串,一次一个字符,打印子字符串:
As others have pointed out, the program as written has undefined behaviour.
If you make a small alteration:
then I believe it is legal, and possible to explain. (EDIT: Actually there are still problems with it. It's
int main()
, and you shouldreturn 0;
at the end. You also need to#include <string.h>
because you are usingstrlen
, and#include <stdio.h>
because you are usingprintf
.)The line
sets
x[0]
(i.e.*x
) tox[4]
(which happens to be the string terminator'\0'
). Thus the first string to be printed is the empty string, because the very first character is the string terminator.We then loop through the string, one character at a time, printing the substrings:
虽然结果是未定义的行为,正如 DeadMG 所说,但我们假设您将 x 声明为 char x[] = "girl"。
您将 4 分配给
n
(因为单词“girl”的长度为 4),并将x[4]
中的值分配给*x< /code> (即
x[0]
),但该值为 '\0'(空终止符)现在循环并打印从 x 到下一个空终止符的单词,但这是第一次,第一个字符是空终止符,所以你得到 没有什么。之后,您可以从递增索引中打印单词。
While the result is undefined behavior, as DeadMG said, let's assume you declared x as
char x[] = "girl"
.You assign 4 to
n
(since the length of the word "girl" is 4), and you assign the value inx[4]
to*x
(which isx[0]
), but this value is '\0' (null terminator)Now you loop and print the word from x to the next null terminator, but the first time, the first char is the null terminator, so you get nothing. after that you print the word from incrementing index.
该代码非常可疑。
*x=x[n]
尝试覆盖文字“girl”,效果会因平台和编译器而异。更正确的是,它应该声明为:然后它不会(不应该)编译。
The code is distictly suspect.
*x=x[n]
attempts to overwrite the literal "girl", and the effect will vary between platforms and compilers. More correctly it should be declared as:and then it will not (should not) compile.