Daniel Hogan
Daniel Hogan

Reputation: 71

How to declare a variable sized 2D arrays global in C?

I'm making a randomized n*n matrix, but I do not know the value of n until the program is already running.

I'm capable of creating the n*n matrices in main() like so:

    double (*m1)[n];
    m1 = malloc(sizeof *m1 * n);

    double (*m2)[n];
    m2 = malloc(sizeof *m2 * n);

But now I must use these matrices outside of main and need them to be global, but I'm completely clueless how to make them global. I intend to read these two matrices with multiple threads and need them easily accessible. I know I can make a struct to pass multiple parameters, but I would need to define a struct with variable length arrays globally so the problem rearises. Thank you for your time.

Upvotes: 3

Views: 2446

Answers (2)

Lundin
Lundin

Reputation: 213513

The correct, proper solution is to not use globals. Allocate the array in the thread which will persist throughout the execution of the whole program.

If that, for reasons unknown, is not an option, then you will have to come up with some solution that stores the array size globally too. You could create a simple ADT for this, such as a struct with a "mangled" 2D array in the form of a flexible array member. Example:

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

typedef struct
{
  size_t x;
  size_t y;
  double array [];
} double_array2d_t;

double_array2d_t* array2d = NULL;

int main()
{
  /* let x and y be some manner of run-time values: */
  int x = 3;
  int y = 2;

  array2d = malloc(sizeof(*array2d) + sizeof(double[x][y]));
  array2d->x = x;
  array2d->y = y;

  double count = 0.0;
  for(int i=0; i<x; i++)
  {
    for(int j=0; j<y; j++)
    {
      array2d->array[i*y + j] = count++;
      printf("%f ", array2d->array[i*y + j]);
    }
    printf("\n");
  }

  ...

  free(array2d);
}

And of course if you access this from multiple threads, you have to protect the data with a mutex as always.

Upvotes: 3

SRIDHARAN
SRIDHARAN

Reputation: 1222

Just declare as double pointer and allocate memory in main. For more details refer this

#include <stdio.h>
int **a;
void fun(int n)
{
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
            printf("%d ",a[i][j]);
    }
}
int main(void) 
{
    int n;
    scanf("%d",&n);
    a = (int **)malloc(n * sizeof(int *));
    for(int i=0;i<5;i++)
    {
        a[i]=(int*)malloc(n*sizeof(int));
    }
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
        {
            scanf("%d",&a[i][j]);
        }
    }
    fun(n);
    return 0;
}

Working Code : https://ideone.com/OMQ4qA

Upvotes: 3

Related Questions