Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - function returns an array

Tags:

arrays

c

methods

I'm writing a method that receives a number l and returns a vector of size l with random numbers. I have this code, but does not work

#include <time.h>    

 int makea (int z) {
    int a1[z];
    int i;

    for (i = 0; i < tam; i++) {
        a1[i]=srand(time(0));
    }
    return a1;
 }

These are the errors that the compiler returns me

arrays1.c: In function 'makea':
arrays1.c:12: error: void value not ignored as it ought to be
arrays1.c:14: warning: return makes integer from pointer without a cast
arrays1.c:14: warning: function returns address of local variable

I think is a problem of pointers... but I'm not really sure

like image 896
patz Avatar asked Sep 22 '26 12:09

patz


2 Answers

A few problems:

  1. Your array is allocated on the stack, meaning that when your function exits, the memory you return will be invalid
  2. In C, you cannot return an array from a function, it must first decay into a pointer.

So, to fix, use malloc and a pointer:

int *makea (int z) {
    int *a1 = malloc(sizeof(int) * z);
    int i;

    srand(time(NULL));
    for (i = 0; i < tam; i++) {
        a1[i]= rand();
    }

    // remember to free a1 when you are done!
    return a1;
}

Also note that using malloc can sometimes basically grant you the 'random number' scenario for free, negating the need to loop through the elements as the value returned from malloc is garbage (and thus random numbers).

However, also note that malloc is implementation-specific, meaning that an implementation could theoretically clear the memory for you before returning it.

like image 63
Richard J. Ross III Avatar answered Sep 24 '26 01:09

Richard J. Ross III


Your best bet is:

  1. Declare the array outside of the routine, and pass it in to initialize it:

    void init_array (int a[], nelms)

  2. Plan B is pass a pointer to a pointer, and have the routine allocate and initialize it

Like this:

void alloc_and_init_array (int **a_pp, int nelms)
{
  *a_pp = malloc (sizeof (int) * nelms);
  ...

... or, equivalently ...

int *
alloc_and_init_array (int nelms)
{
  int *a_p = malloc (sizeof (int) * nelms);
  ...
  return a_p;
like image 34
paulsm4 Avatar answered Sep 24 '26 00:09

paulsm4



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!