Ryan's Blog

C: allocate and assign values to an array of arrays

Posted in programming by ryanlayer on July 28, 2014
void f(int ***A, int r, int c)
{
  int i,j;
  if (*A == NULL) {
    *A = (int **) malloc (r*sizeof(int *));
    for (i = 0; i < r; ++i) {
      (*A)[i] = (int *) malloc (c*sizeof(int));
    }
  }

  for (i = 0; i < r; ++i) {
    for (j = 0; j < c; ++j) {
      (*A)[i][j] += i*10+j;
    }
  }

}

int main()
{
  int i,j,r = 5, c = 3;

  int **A = NULL;

  f(&A, r, c);
  f(&A, r, c);

  for (i = 0; i < r; ++i) {
    for (j = 0; j < c; ++j) {
      printf("%d\n", A[i][j]);
    }
  }
}
Advertisements
Tagged with:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: