使用 char* 增加数组 [C++]

increase array with char* [C++]

本文关键字:C++ 数组 增加数 char 增加 使用      更新时间:2023-10-16

我正在处理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);
}