题目来源:点击打开链接 What is the result of the following program?
char* f(char *str, char ch) { char *it1 = str; char *it2 = str; while (*it2 != '\0') { while (*it2 == ch) { it2++; } *it1++ = *it2++; } return str; } void main(int argc, char *argv[]) { char *a = new char[10]; strcpy(a, "abcdcccd"); cout << f(a, 'c'); } A:abdcccd B:abdd C:abcc D:abddcccd分析:
最开始这道题我也选的B但是仔细分析后发现答案是D的。看下面这段代码: while(*it2 != '\0') { while(*it2 == ch) { it2++; } *it1++ = *it2++; } it1的前两个字符为ab没有异议,当it2的指针指向c时执行 it2++,运行后it2指向d,然后下一个字母不为c,所以it1的指针内复制为d,即此时it1为abd,之后遇到3个c,执行 it2++,直到it2指向d时才将d赋值给it1,也就是此时it1=abdd,但是接下来it2已经为空了,也就是“\0”,所以就不执行循环了,但是it1内本身后面还有cccd,前面的四个字母只是it2覆盖成abdd,所以最终的答案是abddcccd也就是D What is the result of the following program?