我该如何申请的结构失调? [英] How do I apply a structure offset?

查看:184
本文介绍了我该如何申请的结构失调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构

typedef struct foo {
    int lengthOfArray1;
    int lengthOfArray2;
    int* array1;
    int* array2;
} foo;

我要整个结构和数组的内容分配足够的内存。因此,假设每个阵列有长度为5 ...

I need to allocate enough memory for the entire structure and its array's contents. So assuming each array had a length of 5...

foo* bar = (foo*)malloc(sizeof(foo) + (sizeof(int) * 5) + (sizeof(int) * 5));

我现在有指向数组1和数组2在该分配的缓冲区中的正确位置:

I now have to point array1 and array2 to the correct location in that allocated buffer:

bar->array1 = (int*)(&bar->lengthOfArray2 + sizeof(int));
bar->array2 = (int*)(bar->array1 + lengthOfArray2);

这是正确的?

编辑#1

只是为了澄清任何混乱。我试图保持在内存中一个块,而不是三

Just to clear up any confusion: I am trying to keep the memory in one block, and not three.

编辑#2

我不能使用C99作为MSVC 2010编译器不支持它(http://stackoverflow.com/questions/6688895/does-microsoft-visual-studio-2010-supports-c99)。

I cannot use C99 as the MSVC 2010 compiler does not support it (http://stackoverflow.com/questions/6688895/does-microsoft-visual-studio-2010-supports-c99).

推荐答案

继OP的做法本应做的工作:

Following the OP's approach this should do the job:

/* Defining these types allows to change the types without having the need to modify the code. */
typedef int Foo_ArrayElement1_t;
typedef int Foo_ArrayElement2_t;

typedef struct Foo_s {
    size_t lengthOfArray1; /* 'size_t' is the type of choice for array/memory dimensions. */
    size_t lengthOfArray2;
    Foo_ArrayElement1_t * array1;
    Foo_ArrayElement2_t * array2;
} Foo_t;

/*
 * Allocates memory to hold a structure of type Foo_t including size for 
 * 's1' elements referenced by 'array1' and 's2' elements by 'array2'.
 * The arrays' elements are set to 0.
 *
 * Returns a pointer to the freshly allocated memory or NULL if the memory could not 
 * be allocated.
 */
Foo_t * Foo_CreateAndInit(size_t s1, size_t s2)
{
  /* At once allocate all 'Foo_t' (including the memory Foo_t's array pointers shall point to). */
  Foo_t * pfoo = calloc(1,
      sizeof(*pfoo) +
      s1 * sizeof(*(pfoo->array1) + 
      s2 * sizeof(*(pfoo->array2)));
  if (pfoo)
  {
    pfoo->lengthOfArray1 = s1;
    pfoo->lengthOfArray2 = s2;

    /* The first array starts right after foo. */
    pfoo->array1 = (Foo_ArrayElement1_t *) (pfoo + 1); 

    /* The second array starts right after s1 elements of where the first array starts. */
    pfoo->array2 = (Foo_ArrayElement2_t *) (pfoo->array1 + s1); /* That casting here is not 
        necessaryas long as 'Foo_t.array1' and 'Foo_t.array2' point to the same type but makes 
        the code work even if those types were changed to be different. */
  }

  return pfoo;
}

...

Foo_t * foo = Foo_CreateAndInit(5, 5);

这篇关于我该如何申请的结构失调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆