lua-users home
lua-l archive

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

17.01.10, 14:40, "Kuang Chen" <>:

> Sorry I push the wrong button.
>       I would like to define an array with the following structure:
>      typedef struct
>      {
>          int size;
>          double x_values[1];  /* x variable part */
>          double y_values[1];  /* y variable part */
>      } PairArray;
>      As you can see, it is quite similar to the NumArray defined in
> ch28, pil, with the only difference being that there are a pair of
> values (x,y) for each index. The size of PairArray is provided by user
> at run time. Therefore, I wrote a "new" function for PairArray , which
> is again similar to the one on pil:
>      static PairArray PairArray_alloc(lua_State *L, int size)
>      {
>          size_t nbytes = sizeof(PairArray) + 2*sizeof(double)*(size-1);
>          PairArray* p  = (PairArray*)lua_newuserdata(L, nbytes);
>          return p;
>      }
> However,  there is a problem as to how the allocated block of memory
> is divided between x_values and y_values. Are both x_values and
> y_values given n * sizeof(double) , or x_values has 1*sizeof(double)
> and y_values has (2*n-1)*sizeof(double)?  This ambiguity exists in any
> userdata with more than one fields that need memory allocation
> dynamically. Any one has thoughts on this issue?
> Kuang

Hi, Kuang.

If you plan to resize it later, use dynamic allocation:

typedef struct {
  double x;
  double y;
} Pair;

typedef struct PairArray {
  size_t size;
  Pair *pairs;

PairArray *pa = lua_newuserdata(L, sizeof(*pa));
pa->size = arr_size;
pa->pairs = malloc(sizeof(*pa->pairs) * pa->size);

Otherwise, you may save a single allocation:

typedef struct PairArray {
  size_t size;
  Pair pairs[]; // "flexible array member", since C99

PairArray *pa = lua_newuserdata(L, sizeof(*pa) + sizeof(*pa->pairs) * arr_size);
pa->size = arr_size;

In pre-C99 code they used pairs[1] instead, and subtracted 1
from arr_size, because sizeof(*pa) already contained one Pair