Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help with returning a 2D array C++, please

Tags:

c++

I'm trying to create an array and pass it to functions, which then return it, but I don't know the correct way of returning. I've been looking around tutorials and trying stuff out, but haven't managed to solve this. I'm new to C++ and thought it would be similar to Java, but apparently it isn't.

This is where I've gotten:

class MainClass {

public:
    static int countLetterCombinations(string array[], int numberOfWords) {
        // Code
        return totalCombos;
    }


    // This is the function I'm having trouble with.
    static string** sortCombos(string combinations[][3]) {
            // Do something
        return combinations; // This gives converting error.
    }

};


int main() {

// Code

int numberOfCombinations = MainClass::countLetterCombinations(words, numberOfWords);

string combinations[numberOfCombinations][3];

combinations = MainClass::sortCombos(combinations);

// Further code

}

Anyone know how to fix this?

like image 674
Kristjan Avatar asked Dec 10 '25 09:12

Kristjan


1 Answers

You need to use a vector. C++ stack-based arrays cannot be dynamically sized- oh, and you can't convert [][] to **, the conversion only works for the first dimension. Oh, and you can't assign to arrays, either.

The simple rule is, in C++, never use primitive arrays- they're just a headache. They're inherited from C, which actually defined a lot of it's array behaviour for source compatibility with B, which is insanely old. Use classes that manage dynamic memory for you, like std::vector, for dynamically sizable arrays.

std::vector<std::array<std::string, 3>> combinations(numberOfCombinations);

static void sortCombos(std::vector<std::array<std::string, 3>>& combinations) {
        // Do something
} // This function modifies combinations in-place and doesn't require a return.

Oh, and you really don't have to make functions static class members- they can just go in the global namespace.

like image 200
Puppy Avatar answered Dec 13 '25 00:12

Puppy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!