1

I want to create multiple arrays based on the iterations of a loop in C.

For example:

int i, size;

for ( i =0; i< 10; i++)
{
  size = i * 100
  create_array(i,size); // This loop iterates 9 times creating 9 different arrays
}

void create_array(int name, int size)
{
  double *array_name = (double*) malloc (size*sizeof(double));
  // perform operations on array_name

}

Therefore we end up with 9 arrays namely array_0,array_1, .... array_9. Can this be accomplished in C or Fortran (not C++)?

1
  • You are not returning array_name from create_array. Where do you want to have array_0, array_1 etc.? Commented Jun 19, 2013 at 15:11

3 Answers 3

2

Fortran example:

program create_arrays


type ArrayHolder_type
   integer, dimension (:), allocatable :: IntArray
end type ArrayHolder_type

type (ArrayHolder_type), dimension (:), allocatable :: Arrays

integer :: i, j

allocate ( Arrays (4) )

do i=1, 4
   allocate ( Arrays (i) % IntArray (2*i) )
end do

do i=1, 4
   do j=1, 2*i
      Arrays (i) % IntArray (j) = i+j
   end do
   write (*, *)
   write (*, *) i
   write (*, *) Arrays (i) % IntArray
end do


end program create_arrays
Sign up to request clarification or add additional context in comments.

Comments

1

An array of arrays?

double *arrays[10];

for (int i = 0; i < 10; i++)
    arrays[i] = malloc(some_size * sizeof(double));

Now you have an array of "arrays", conveniently named arrays[0] to arrays[9].


If you want the amount of arrays to be dynamic as well, use double-pointer:

double **arrays;

arrays = malloc(number_of_arrays * sizeof(double *));

/* Allocate each sub-array as before */

1 Comment

typo mistake in second malloc() , instead of *
0

You can do it but instead of having the name array_0,array_1, .... array_9. you will have a like Matrix ( you can acces to your arrays array[1], array[2]...) by doing this

    int i, size;

double ** array = (double**) malloc (size*sizeof(double*));
for ( i =0; i< 10; i++)
{
  size = i * 100
  array[i] = create_array(size); 
}

double* create_array( int size)
{
  double *array_name = (double*) malloc (size*sizeof(double));
  // perform operations on array_name;
  return arrayname;

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.