Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return array of arrays, with different sizes form function

I’m trying to create array of arrays with different sizes and return it, so I can work with it later. Is it even possible? I was trying to do something like this:

#include <iostream>

int* fun(){
    int a[] = {3, 2, 1};
    int b[] = {5, 4};
    int *arr[] = {a, b};

    return *arr;
}

int main() {
    int *array = fun();
    printf("\n%d, %d, %d", *(array), *(array + 1), *(array + 2));
    // this one prints: 3, 2, 1
    printf("\t%d, %d", *(array + 3), *(array + 4));
    // this one prints random numbers
    return 0;
}

I want to access both arrays.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I would refactor to use std::vector instead of c-style arrays

#include <iostream>
#include <vector>

std::vector<std::vector<int>> fun(){
    std::vector<int> a{3, 2, 1};
    std::vector<int> b{5, 4};
    return {a, b};
}

int main() {
    std::vector<std::vector<int>> values = fun();
    printf("\n%d, %d, %d", values[0][0], values[0][1], values[0][2]);
    printf("\t%d, %d", values[1][0], values[1][1]);
    return 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading