[ale] C Programming Question

Joseph A. Knapka jknapka at earthlink.net
Tue Mar 6 14:43:05 EST 2001


So you want something like

char* my_ary[10][10];

only dynamically allocated?

The easiest thing you can do is to dynamically allocate a 1D array
that's
big enough, and then dereference it as if it were 2D.
This is essentially what the compiler does with static multidimensional
array declarations. So:

--cut here--
#include <stdio.h>
#include <memory.h>

/* This typedef makes the cast of my_2d_ary comprehensible :-)
   Type cpten is a pointer to an array of 10 character pointers.
 */
typedef char* cpten[10]; 

int main(void)
{
  char** my_1d_ary = (char**)(malloc(100*sizeof(char*)));
  cpten * my_2d_ary = (cpten*)my_1d_ary;
  int i,j;

  for (i=0; i<100; ++i) {
      my_1d_ary[i] = (char*)(i);
  }
  for (i=0; i<10; ++i) {
    for (j=0; j<10; ++j) {
      printf("my_2d_ary[%d][%d] = %d\n",i,j,(int)(my_2d_ary[i][j]));
    }
  }

  return 0;
}
--cut here--


Alternatively, you can manually allocate each dimension of the
array separately, which IMO is a pain in the ass. That is,
allocate an array of char**, and then for each element of
that array, allocate an array of char*, thus:

--cut here--
#include <stdio.h>
#include <memory.h>

typedef char* cpten[10]; 

int main(void)
{
  char*** my_1st_dim = (char***)(malloc(10*sizeof(char**)));
  int i,j;

  for (i=0; i<10; ++i) {
    my_1st_dim[i] = (char**)(malloc(10*sizeof(char*)));
  }

  for (i=0; i<10; ++i) {
    for (j=0; j<10; ++j) {
      my_1st_dim[i][j] = (char*)(i+j);
    }
  }

  for (i=0; i<10; ++i) {
    for (j=0; j<10; ++j) {
      printf("my_1st_dim[%d][%d] = %d\n",i,j,(int)(my_1st_dim[i][j]));
    }
  }

  return 0;
}
--cut here--

HTH,

-- Joe

Terry Lee Tucker wrote:
> 
> Hello ALE:
> 
> Is there a way to dynamically allocate a two dimensional array of
> pointers? If so, could someone show me a simple example?
> 
> Thanks...
> --
> Sparta, NC 28675 USA
> 336.372.6812
> http://www.esc1.com
> The Gates of hell shall NOT prevail...
> --
> To unsubscribe: mail majordomo at ale.org with "unsubscribe ale" in message body.

-- Joe Knapka
--
To unsubscribe: mail majordomo at ale.org with "unsubscribe ale" in message body.





More information about the Ale mailing list