20180529

What is the result of the following program?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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');
}
abdcccd
abdd
abcc
abddcccd
Access Violation

答案D 错选B
最开始这道题我也选的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
 
posted @ 2018-06-02 20:05  Kxzh  阅读(124)  评论(0编辑  收藏  举报