Re: dynamically growing 2D aray of structues



A GPtrArray of GPtrArrays?

#include <glib.h>

typedef struct {
  char *p;
} mystruct;

static void
free_mystruct (gpointer data)
{
  mystruct *p = data;

  if (p == NULL)
    return;

  g_print ("Freeing struct %p: %s\n", p, p->p);

  g_free (p->p);
  g_free (p);
}

static void
free_sub_array (gpointer data)
{
  GPtrArray *a = data;

  if (data != NULL)
    g_ptr_array_free (a, TRUE);
}

static gpointer
new_mystruct (const char *data)
{
  mystruct *p = g_slice_new (mystruct);

  p->p = g_strdup (data);

  g_print ("Created struct %p: %s\n", p, p->p);

  return p;
}

static void
set_at (GPtrArray *a,
        int        x,
        int        y,
        char      *data)
{
  GPtrArray *b;

  if (x >= a->len)
    g_ptr_array_set_size (a, x + 1);

  if (g_ptr_array_index (a, x) == NULL)
    g_ptr_array_index (a, x) = g_ptr_array_new_with_free_func (free_mystruct);

  b = g_ptr_array_index (a, x);

  if (y >= b->len)
    g_ptr_array_set_size (b, y + 1);

  free_mystruct (g_ptr_array_index (b, y));
  g_ptr_array_index (b, y) = new_mystruct (data);
}

static const mystruct *
get_at (GPtrArray *a,
        int        x,
        int        y)
{
  GPtrArray *b;

  if (x >= a->len ||
      g_ptr_array_index (a, x) == NULL)
    return NULL;

  b = g_ptr_array_index (a, x);

  if (y >= b->len ||
      g_ptr_array_index (b, y) == NULL)
    return NULL;

  return g_ptr_array_index (b, y);
}

int
main (int argc, char **argv)
{
  GPtrArray *twodee = g_ptr_array_new_with_free_func (free_sub_array);
  int i, j;

  set_at (twodee, 2, 3, "2,3");
  set_at (twodee, 3, 2, "3,2");
  set_at (twodee, 2, 0, "2,0");
  set_at (twodee, 6, 8, "6,8");
  set_at (twodee, 3, 2, "anew");
  set_at (twodee, 1, 3, "1,3");

  for (i = 0; i < 9; i++)
    {
      for (j = 0; j < 9; j++)
        g_print ("%4s ", get_at (twodee, i, j) ? get_at (twodee, i,
j)->p : "-");
      g_print ("\n");
    }

  g_ptr_array_free (twodee, TRUE);

  return 0;
}

--tml


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]