简体   繁体   中英

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.

The code I've written is, partially, this (it's about 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.

|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. So I can't understand what the error message is saying.

Could you help me?

Use a 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.

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.

As general rule you should not use arrays, pointers or new in C++ programs. Of course there are lots of exceptions, but your first choice should be to use std::vector instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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