0

I have an array that was created within a function, I want to use it in a different function but can't seem to figure out how.

If it helps at all, here is the function with the array in it. I want to use roll[] within a different function.

int roll_5_array(void)
{
    int i = 0, roll[5]; //Declaring array

    for (; i < 5; i = i + 1) //Repeat 5 times
    {
        int outcome = 0;
        outcome = roll_die(); //Roll die

        roll[i] = outcome;
    }

}


With my current knowledge, I can only come up with a few possible solutions to this:

  • Make the array global, which seems unnecessary and redundant.
  • Pass the array as a pointer, if that's even possible.
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Bacleo
  • 1
  • 2
  • Do you want to use it in the `roll()` function? If so, then yes -- pass an `int*` and a `size_t` length. https://stackoverflow.com/questions/6567742/passing-an-array-as-an-argument-to-a-function-in-c – JohnFilleau Mar 15 '23 at 20:35

2 Answers2

1

You declared a local array with automatic storage duration

int roll_5_array(void)
{
    int i = 0, roll[5]; //Declaring array

It will not be alive after exiting the function.

If you want to return it from the function you need to allocate it dynamically as for example

int * roll_5_array(void)
{
    int i = 0;
    int *roll = malloc( 5 * sizeif( int ) );

    //...
    return roll;
} 

To do so you need to include header <stdlib.h>.

You will need to free the array using a pointer that points to the allocated array by means of calling function free when the array will not be required any more.

Pay attention to that your original function returns nothing though its return type is not void

int roll_5_array(void)
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

You can do this two ways

  1. Returning pointer to the array
int *func(void)
{
    int *arr = malloc(5 * sizeof(*arr));
    /* ... */
    return arr;
}

int *func(void)
{
    static int arr[5];
    /* ... */
    return arr;
}

Or by passing the pointer to pointer.

void func(int **ptr)
{
    int *arr = malloc(5 * sizeof(*arr));
    /* ... */
    *ptr = arr;
}

void func(int **ptr)
{
    static int arr[5];
    /* ... */
    *ptr = arr;
}
0___________
  • 60,014
  • 4
  • 34
  • 74