c++优化,改错:void cat(char * &p, const char *str) { if (p != nullptr) { int len = strlen(p) + 1+strlen(str); for (int i =strlen(p),j=0; i<len; i++,j++) { p[i++] = str[j]; } } else { p = new char[strlen(str) + 1]; strcpy_s(p, strlen(str) + 1, str); } }
时间: 2024-03-22 21:38:31 浏览: 25
这段代码的问题在于使用了错误的循环条件以及错误的下标增量。
首先,在 for 循环中,应该用 `i < len` 作为循环条件,而不是 `i = len`,因为 `i = len` 会使循环多执行一次,导致数组越界。
其次,在循环体中,应该将 `i++` 和 `j++` 分别写在两个语句中,否则会导致 `i` 和 `j` 的增量不同步,导致程序出错。
改正后的代码如下:
```c++
void cat(char *&p, const char *str) {
if (p != nullptr) {
int len = strlen(p) + 1 + strlen(str);
char *temp = new char[len];
int i, j;
for (i = 0; p[i] != '\0'; i++) {
temp[i] = p[i];
}
for (j = 0; str[j] != '\0'; j++) {
temp[i++] = str[j];
}
temp[i] = '\0';
delete[] p;
p = temp;
} else {
p = new char[strlen(str) + 1];
strcpy_s(p, strlen(str) + 1, str);
}
}
```
在上述代码中,我使用了一个临时数组 `temp` 来存储拼接后的字符串,并在最后将其复制到 `p` 中,以保证程序的正确性。同时,在使用 `new` 为 `temp` 分配内存之后,也需要在不再使用时使用 `delete[]` 进行释放,以避免内存泄漏。