我正在处理 C++ 中的动态数组。帮忙看看下面的代码。
我正在尝试一个一个地读取字符并制作 C 字符串。如果数组大小不够,我会增加它。但是函数 increaseArray 会出错并返回一个包含其他字符的字符串。我哪里错了?
void increaseArray(char* str, int &size){
char* newStr = new char[size * 2];
for (int i = 0; i < size; i++){
newStr[i] = str[i];
}
size *= 2;
delete[] str;
str = newStr;
}
char* getline()
{
int size = 8;
char* str = new char[size];
char c;
int index = 0;
while (c = getchar()) {
if (index == size) increaseArray(str, size);
if (c == '\n') {
str[index] = '\0';
break;
};
str[index] = c;
index++;
}
return str;
}
最佳答案
在函数 increaseArray
中,您将 newStr
分配给 str
但是 str
是 中指针的本地拷贝>increaseArray
函数,因此更改在其外部不可见。
最简单的解决方法是将 increaseArray
签名更改为:
void increaseArray(char*& str, int &size)
因此将传递对指针的引用,因此 increaseArray
内对 str
的更改将在其外部可见。
关于c++ - 用 char* 增加数组 [C++],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41780666/