astrotyconn

 

腾讯面试题的菜鸟解法

原题:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
	int a = 3, b = 5;
	
	printf(&a["Hi!Hello"], &b["fun/super"]);
         printf("\n");
	printf("%c%c%c%c", 1["wst"], 2["www"], 0["ddd"], 5["ewewrew"]);
	
	return 0;
}

 问输出什么?对于这种不常见用法的很多人还是不知道的!公共主页的做法是反汇编,由于本人对汇编不熟,所以望而生畏。但我觉得本题不用汇编一样可以解出来,只要你对C语言中数组与指针的关系很了解就行。

比如:a[2] <==> *(a+2) <==> 2[a],当然为了代码的美观与可读性,强烈不建议用最后一种,但你必须知道!

所以a["Hi!Hello"] <==> "Hi!Hello"[a] ==>'H'(注意不是第一个H,是第二个H)

      b["fun/super"] <==> "fun/super"[b] ==>'u'

      1["wst"] <==> "wst"[1]

      2["www"] <==> "www"[2]

      0["ddd"] <==> "ddd"[0]

      5["ewewrew"] <==> "ewewrew"[5]

所以我们改写上面的代码

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
	int a = 3, b = 5;
	
	printf(&"Hi!Hello"[a], &"fun/super"[b]);
	printf("\n");
	printf("%c%c%c%c", "wst"[1], "www"[2], "ddd"[0], "ewewrew"[5]);
	
	return 0;
}

 

其实都是一样的道理!

输出结果是: Hello

                swde

至于为什么只输出Hello而不输出uper,我查了下:

If there are more arguments than there are format specifications, the extra arguments are ignored.

超过格式化符号个数的参数,将被忽略。

The results are undefined if there are not enough arguments for all the format specifications.

如果没有足够的参数对应其格式化,其结果将是不确定的。

 

 

posted on 2012-01-08 15:20  astrotyconn  阅读(110)  评论(0)    收藏  举报

导航