首页 > 解决方案 > 我应该如何在 C++ 中动态分配字符串指针?

问题描述

大家好! 我正在尝试为 C++ 中的字符串指针动态分配空间,但我遇到了很多麻烦。

我编写的代码部分是这样的(关于 RadixSort-MSD):

class Radix
{
    private:
        int R = 256;
        static const int M = 15;
        std::string aux[];
        int charAt(std::string s, int d);
        void sortR(std::string a[]);
    public:
        void sortR(std::string a[], int left, int right, int d);
};

这是有问题的部分:

void Radix::sortR(std::string a[])
{
    int N = sizeof(a)/sizeof(std::string*);
    aux = new std::string[N];  //Here is the problem!
    sortR(a, 0, N-1, 0);
}

当我尝试编译我的项目时出现的错误如下,它与变量“aux”有关,它是一个字符串指针。

|15|error: incompatible types in assignment of 'std::__cxx11::string* {aka std::__cxx11::basic_string<char>*}' to 'std::__cxx11::string [0] {aka std::__cxx11::basic_string<char> [0]}'|

我是一个完全不懂巴西 C++ 的学生。所以我无法理解错误消息在说什么。

你可以帮帮我吗?

标签: c++dynamic-memory-allocationradix-sort

解决方案


使用std::vector. 改变这个

std::string aux[];

对此

std::vector<std::string> aux;

和这个

void Radix::sortR(std::string a[])
{
    int N = sizeof(a)/sizeof(std::string*);
    aux = new std::string[N];  //Here is the problem!
    sortR(a, 0, N-1, 0);
}

对此

void Radix::sortR(const std::vector<std::string>& a)
{
    aux.resize(a.size());  //No problem!
    sortR(a, 0, a.size()-1, 0);
}

您还必须更改其他版本sortR以使用向量而不是指针。

您的代码无法工作,因为您无法将数组传递给 C++ 中的函数,因此此代码sizeof(a)/sizeof(std::string*)不起作用,因为您的sortR函数内部a是一个指针。

作为一般规则,您不应new在 C++ 程序中使用数组、指针。当然有很多例外,但您的首选应该是使用std::vector


推荐阅读