Home > Back-end >  Get two arrays from function and store them in different data type array in C
Get two arrays from function and store them in different data type array in C

Time:12-19

I have a function which contains more than one array and I want to use those two arrays in my main function in this way

void fun ()    //which data type should I place here int OR char ?
{
    int array[4]={1,2,3,4}
    char array2[3]={'a','b','c'}

    return array,array2;
}
int main(){

    int array1[4];
    char array2[3];


    array1=fun();  is it possible to get these array here ?
    array2=fun();
}

CodePudding user response:

If you really want to return arrays, you could put them in a std::pair of std::arrays:

#include <array>
#include <utility>

auto fun() {
    std::pair<std::array<int, 4>, std::array<char, 3>> rv{
        {1, 2, 3, 4},
        { 'a', 'b', 'c' }
    };

    return rv;
}

int main() {
    auto[ints, chars] = fun();
} 

CodePudding user response:

Use std::tuple of std:arrays:

#include <iostream>
#include <array>
#include <tuple>

std::tuple<std::array<int, 4>, std::array<char, 3>> fun() 
{
    std::array<int, 4> a1 = { 1, 2, 3, 4 };
    std::array<char, 3> a2 = { 'a', 'b', 'c' };
    return std::make_tuple(a1, a2);
}

int main()
{
    auto mixedArrays = fun();
    
    for (const auto& i : std::get<0>(mixedArrays))
    {
        std::cout << i << std::endl;
    }
    
    for (const auto& i : std::get<1>(mixedArrays))
    {
        std::cout << i << std::endl;
    }
}

Demo

This way you can extend the code to make fun() return more stuff in the future if need be.

CodePudding user response:

Using a struct, code would look like this (using range based for loops for output).

#include <array>
#include <iostream>

// struct holding two arrays with clear names
struct myfun_retval_t
{
    std::array<int, 4> integers;
    std::array<char, 3> characters;
};

// function returning the struct with two arrays
myfun_retval_t myfun()
{
    myfun_retval_t retval
    {
        {1,2,3,4},
        {'a','b','c'}
    };

    return retval;
}

int main()
{
    // call function and store result
    auto retval = myfun();

    // then output content, using clear readable names for the arrays

    for (const int value : retval.integers)
    {
        std::cout << value << " ";
    }
    std::cout << "\n";

    for (const char c : retval.characters)
    {
        std::cout << c << " ";
    }

    return 0;
}

CodePudding user response:

Pass pointers to your arrays in main to your function

Like this

void fun(int* array, char* array2)
{
    ...
}

int main()
{
    int array1[4];
    char array2[3];
    fun(array1, array2);
}

Hopefully that will get you started, but really you need to read about arrays and pointers and function parameters in your C book. This is a complicated topic, and one that many newbies get wrong.

  • Related