views:

66

answers:

3

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(double));
   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

+1  A: 

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

fazo
Is this C code, I havent come across the 'struct' thing yet :S
Jack Medley
yes, it's c and sorry, but i have problem with 'indenting' it
fazo
Ah ok, I think this is a different solution to the one I was aiming for (with double pointers) but if it aint broken dont fix it! cheers
Jack Medley
+1  A: 

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;
}
John Bode
OK, so then lets say I set this up to be 3 rows and 'N+1' columns. I would know how to dereference one pointer in main i.e. get to the data structure but then how do i specify that its the second row im trying to access (for instance).
Jack Medley
@Jack Medley: If you have `T **x = alloc(3, N + 1);` then `x[1]` is the second row (and `x[1][50]` is the 51st element of the second row).
caf
+1  A: 

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.

btfx