简体   繁体   English

我应该如何在 C++ 中动态分配字符串指针?

[英]How should I dynamically allocate string pointers in C++?

Hello, everyone!大家好! I'm trying to dynamically allocate space for a string pointer in C++, but I'm having much trouble.我正在尝试为 C++ 中的字符串指针动态分配空间,但遇到了很多麻烦。

The code I've written is, partially, this (it's about RadixSort-MSD):我写的代码部分是这样的(它是关于 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);
};

And here is the problematic part:这是有问题的部分:

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);
}

The error that apears when I try to compile my project is below, and it's about the variable "aux", which is a string pointer.当我尝试编译我的项目时出现的错误如下,它与变量“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]}'|

I'm a completely noob brazilian C++ student.我是一个完全菜鸟的巴西 C++ 学生。 So I can't understand what the error message is saying.所以我无法理解错误消息在说什么。

Could you help me?你可以帮帮我吗?

Use a std::vector .使用std::vector Change this改变这个

std::string aux[];

to this对此

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

and this和这个

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);
}

to this对此

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

You'll also have to change the other version of sortR to use vectors instead of pointers.您还必须更改sortR的其他版本以使用向量而不是指针。

Your code could not work because you cannot pass an array to a function in C++, so this code sizeof(a)/sizeof(std::string*) does not work because inside your sortR function a is a pointer.您的代码无法工作,因为您无法将数组传递给 C++ 中的函数,因此此代码sizeof(a)/sizeof(std::string*)不起作用,因为在sortR函数内部a是一个指针。

As general rule you should not use arrays, pointers or new in C++ programs.作为一般规则,您不应在 C++ 程序中使用数组、指针或new Of course there are lots of exceptions, but your first choice should be to use std::vector instead.当然有很多例外,但您的首选应该是使用std::vector

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM