【发布时间】:2011-09-04 14:52:27
【问题描述】:
我知道这是基本内容的一部分,但我被卡住了:-( 有人可以帮帮我吗?
方案一:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a=1,b=2,c;
c=(a+b)++;
}
为什么输出错误?需要左值吗?
方案二:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *p1="name";
char *p2;
p2=(char*)malloc(20);
memset(p2,0,20);
while(*p2++=*p1++);
printf("%s\n",p2);
}
为什么输出是空字符串?而如果我颠倒递增的顺序,即:while(++*p2=++*p1);,为什么会出现左值错误?
【问题讨论】:
-
"kiss",避免使用 while(*p2++=*p1++);最好将该行分成更易读的多行,并带有清晰的“循环直到”、“inc”和复制部分。而不是一次完成。
-
@Johan:如果事情这么简单,它就不会成为棘手的面试问题的一部分:-)
-
你对这个问题是正确的(并且要学习一些新东西),但从长远来看,更简单的代码往往会更好;)
标签: c pointers lvalue post-increment