我无法理解以下C代码的输出:
#include<stdio.h>
main()
{
char * something = "something";
printf("%c", *something++); // s
printf("%c", *something); // o
printf("%c", *++something); // m
printf("%c", *something++); // m
}
请帮助:)
答案 0 :(得分:6)
有关详细信息,请参阅http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence
printf("%c", *something++);
获取*的东西,然后递增它(&#39; s&#39;)
printf("%c", *something);
获取char(现在是第二个,因为最后一个语句中的增量(&#39; o&#39;)
printf("%c", *++something);
增加然后获得新职位的字符(&#39; m&#39;)
printf("%c", *something++);
获取*某个字符处的char,然后将其递增(&#39; m&#39;)
答案 1 :(得分: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++)
与第一个答案相同。
另请注意printf中每个字符串末尾的'\n'
。它使输出缓冲区刷新并使行打印。始终在printf的末尾使用\n
。
您可能还想查看 this question 。
答案 2 :(得分: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
答案 3 :(得分:0)
始终使用顺时针规则clockwise rule
printf("%c\n", *something++);
根据您将首先遇到的规则*所以得到值然后++表示增量
在第三种情况printf("%c\n", *something++);
所以根据图像增加值++然后得到值*