开发者

Getting a subroutine to return three seperate arrays of random numbers in C

开发者 https://www.devze.com 2023-01-10 06:31 出处:网络
I currently have code for a subroutine to return a pointer to an array.This array is a list of random numbers for a one dimensional monte-carlo integral.I am now trying to do a multi dimensional equiv

I currently have code for a subroutine to return a pointer to an array. This array is a list of random numbers for a one dimensional monte-carlo integral. I am now trying to do a multi dimensional equivalent which requires 3 arrays of random numbers and instead of having a separate subroutine for each I'm trying to make one which returns a 3 by N + 1 array. Could somebody please help me with the coding for this. A mate mentioned I would need a double pointer but most web sources have been unhelpful thus far. Here is my single array code:

double* rdm_Y(void)
{
   double* Random_number_list_Y = calloc(N + 1, sizeof(dou开发者_如何学JAVAble));
   int i;
   sleep(1);
   srand(time(NULL));
   for (i = 1; i <= N; i++) {
      Random_number_list_Y[i] = (float) rand() / (float) RAND_MAX;
   }
   return Random_number_list_Y;
}

Many Thanks! Jack Medley


The general pattern for dynamically allocating a 2D array of type T (where T can be int, double, etc.) is

#include <stdlib.h>

T **alloc(size_t rows, size_t columns)  
{
  T **arr = malloc(sizeof *arr, rows); // type of *arr is T *
  if (arr)
  {
    size_t i;
    for (i = 0; i < rows; i++)
    {    
      arr[i] = malloc(sizeof *arr[i], columns); // type of *arr[i] is T
      if (arr[i])
      {
        size_t j;
        for (j = 0; j < columns; j++)
        {
          arr[i][j] = initial_value_for_this_element;
        }
      }
    }
  }
  return arr;
}


Try:

struct res{
 double *arr1, *arr2, *arr3;
};
main(){
 struct res r;
 r.arr1 = rdm_Y();
 r.arr2 = rdm_Y();
 r.arr3 = rdm_Y();
 // in r you have 3 pointers to 3 separate arrays
}

or something like this


The three methods I can think of are:

  1. A *double to a 1D array of size 3xN (you can just pretend it's three arrays)
  2. A **double to an array of three *doubles, each one pointing to an array of N
  3. A struct containing three *doubles, each one pointing to an array of N

If you don't like pretending for method 1 you can declare two more *doubles and set them to the return value + N and + 2N respectively. Also don't forget to free() you should have 1, 4, and 3 free()s to do for each of the methods respectively.

0

精彩评论

暂无评论...
验证码 换一张
取 消