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

Time:11-09

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.

CodePudding user response:

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;
}
  •  Tags:  
  • c
  • Related