【问题标题】:increase array with char* [C++]用 char* [C++] 增加数组
【发布时间】:2017-06-06 10:43:24
【问题描述】:

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

【问题讨论】:

  • 这个“str = newStr;”将局部变量 str 设置为 newStr。该局部变量立即被丢弃。你想要一个指向指针或引用。
  • 你为什么不用std::string 甚至std::vector&lt;char&gt; ??
  • “我正在尝试逐个读取字符并制作C字符串。如果数组大小不够,我会增加它”字面意思是@987654324 @是为了。您为什么不使用它并省去麻烦呢?您的代码无法通过我团队的审核。

标签: c++ arrays pointers dynamic char


【解决方案1】:

在函数increaseArray 中,您将newStr 分配给str,但是strincreaseArray 函数中指针的本地副本,因此更改在其外部不可见。

最简单的解决方法是将increaseArray签名更改为:

void increaseArray(char*&amp; str, int &amp;size)

因此对指针的引用将被传递,因此在increaseArray 内部对str 的更改将在其外部可见。

【讨论】:

  • 谢谢,真的很有帮助。对指针和引用有点困惑。
【解决方案2】:

你可以这样做。 很简单..

#include <string.h>
#include <stdlib.h>
using namespace std;
void increaseArray(char* &str, int size){
     str = (char *)realloc(str,size*2);
}

【讨论】:

  • 不幸的是,它并没有多大帮助,因为您忽略了 realloc 返回的指针。
  • @ForceBru 我忘了。我已经对此进行了必要的更改。
  • 其实,由于OP使用new[]分配内存,他不能根据this answer使用realloc
猜你喜欢
  • 2018-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-22
  • 2013-08-18
  • 1970-01-01
  • 1970-01-01
  • 2018-09-15
相关资源
最近更新 更多