Home > database >  C how to return arrays from multiple functions?
C how to return arrays from multiple functions?

Time:10-08

I am trying to make a program that first creates an array in another function, returns it and then calls another function that shuffles the contents of the array and returns it. However I am struggling to do this in C since I do not quite understand the array pointer system that has to be used here.

So far my code doesnt return the values 1-20 from makeArray() but instead returns an array full of 0s and I have a feeling it has to do with the c's array pointer system.

Any help would greatly be appreciated! Thank you in advance

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int arrShuffle();



int arrShuffle(int * arr) {
    int arr[21];

    // shuffle array
    for(int j=0; j<20; j  ) {
        int randInd = (rand() % 20)   1;
        int temp = arr[j];
        arr[j] = arr[randInd];
        arr[randInd] = temp;
    }
    return arr;
}


int makeArray() {
    int arr[21];
    // make array of 1-20
    for(int i=0; i < 20; i  ) {
        arr[i] = i   1;
    }
    return arr;
}


void main() {
    int *orgArr;
    int *modArr;
    srand(time(NULL));

    orgArr = makeArray();
    for(int i=0; i < 20; i  ) {
        printf("OrgArr: %d\n", orgArr);
    }
    modArr = arrShuffle(orgArr);
}

CodePudding user response:

You cannot use variables with automatic storage (aka local ones). You must allocate the array so the memory remains valid after the function ends:

int* makeArray() {
    int *arr = calloc(21, sizeof *a);
    // make array of 1-20
    for(int i=0; i < 20; i  ) {
        arr[i] = i   1;
    }
    return arr;
}

Remember to release the array when it is no longer used:

int main() {
    int *orgArr;
    ...
    orgArr = makeArray();
    ...
    free(orgArr);
}

CodePudding user response:

As tstanisl pointed out in their answer, a possible solution is to use dynamic memory allocation. My answer, instead, will give you yet another solution: using an array passed by the caller.

NOTE: both solutions are valid and their usefulness depends on the specific needs of your program. There's no "right" universal solution.

void makeArray(int arr[], size_t len) {
  for (size_t i = 0; i < len; i  = 1) {
    arr[i] = (int) (i   1);
  }
}

void cloneAndModifyArray(const int orig[], int new[], size_t len) {
  for (size_t i = 0; i < len; i  = 1) {
    new[i] = orig[i] * 2; // or some other modification
  }
}

And you use it like this:

#define ARR_LEN (100)

int main(void) {
  int arr[ARR_LEN];

  makeArray(arr, ARR_LEN);

  int modified_arr[ARR_LEN];

  cloneAndModifyArray(arr, modified_arr, ARR_LEN);

  return 0;
}
  • Related