使用 char* 增加数组 [C++]
increase array with char* [C++]
我正在处理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] = ' ';
break;
};
str[index] = c;
index++;
}
return str;
}
在函数increaseArray
中,您将newStr
分配给str
但是str
是函数中指针increaseArray
本地副本,因此更改在其外部不可见。
最简单的解决方法是将increaseArray
签名更改为:
void increaseArray(char*& str, int &size)
,将对指针的引用传递,因此对str
内部increaseArray
的更改将在其外部可见。
你可以这样做。它很简单..
#include <string.h>
#include <stdlib.h>
using namespace std;
void increaseArray(char* &str, int size){
str = (char *)realloc(str,size*2);
}
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '