1

我无法理解以下 C 代码的输出:

#include<stdio.h>
main()
{
   char * something = "something";
   printf("%c", *something++);  // s
   printf("%c", *something);    // o
   printf("%c", *++something);  // m
   printf("%c", *something++);  // m
}

请帮忙 :)

4

4 回答 4

6

有关详细信息,请参阅http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence

printf("%c", *something++);

在 *something 处获取字符,然后将其递增('s')

printf("%c", *something);

只需获取 char (现在是第二个,由于最后一个语句('o')中的增量

printf("%c", *++something);

递增然后获取新位置的字符('m')

printf("%c", *something++);

在 *something 处获取字符,然后将其递增('m')

于 2012-11-12T05:24:36.757 回答
6

这很简单。

char * something = "something";

指针赋值。

printf("%c\n", *something++);//equivalent to *(something++)

指针递增,但递增前的值被取消引用,因为它是后递增的。

printf("%c\n", *something);//equivalent to *(something)

在前一个语句中的增量之后,指针现在指向“o”。

printf("%c\n", *++something);//equivalent to *(++something)

指针递增指向“m”并在递增指针后取消引用,因为这是预递增的。

printf("%c\n", *something++);//equivalent to *(something++)

和第一个答案一样。还要注意'\n'printf 中每个字符串的末尾。它使输出缓冲区刷新并打印行。始终\n在 printf 的末尾使用 a。

你可能也想看看这个问题

于 2012-11-12T05:24:38.943 回答
4
// main entrypoint
int main(int argc, char *argv[])
{
    char * something = "something";

    // increment the value of something one type-width (char), then
    //  return the previous value it pointed to, to be used as the 
    //  input for printf.
    // result: print 's', something now points to 'o'.
    printf("%c", *something++);

    // print the characer at the address contained in pointer something
    // result: print 'o'
    printf("%c", *something);

    // increment the address value in pointer something by one type-width
    //  the type is char, so increase the address value by one byte. then
    //  print the character at the resulting address in pointer something.
    // result: something now points at 'm', print 'm'
    printf("%c", *++something);

    // increment the value of something one type-width (char), then
    //  return the previous value it pointed to, to be used as the 
    //  input for printf.
    // result: print 's', something now points to 'o'.
    printf("%c", *something++);
}

结果:

somm
于 2012-11-12T05:28:45.720 回答
0

始终使用顺时针规则顺时针规则

printf("%c\n", *something++);

根据您将首先遇到的规则 * 所以获取值然后 ++ 表示递增

在此处输入图像描述

第三种情况 printf("%c\n", *something++);

在此处输入图像描述

所以根据图像递增值++,然后得到值*

于 2012-11-12T05:33:07.693 回答