动态分配C结构?

pf.*_*pf. 7 c c++ memory allocation

我想动态分配一个C结构:

typedef struct {
    short *offset;
    char *values;
} swc;
Run Code Online (Sandbox Code Playgroud)

'offset'和'values'都应该是数组,但它们的大小在运行时才会被识别.

如何为我的struct和struct的数组动态分配内存?

spu*_*erh 19

swc *a = (swc*)malloc(sizeof(swc));
a->offset = (short*)malloc(sizeof(short)*n);
a->values = (char*)malloc(sizeof(char)*n);
Run Code Online (Sandbox Code Playgroud)

其中n =每个数组中的项数,a是新分配的数据结构的地址.在free()之前不要忘记free()偏移量和值.

  • 其次,出于同样的原因,你应该使用`sizeof(*a)`和`sizeof(*a-> offset)`而不是`sizeof(swc)`和`sizeof(short)`.如果`a`的类型改变(或者更可能是`a-> offset'的类型从`short`变为`long`),使用变量而不是类型将允许你只改变那条线声明变量,而不是更改`malloc()`和`realloc()`的所有行.如果它们都从变量(或`struct`成员)中推断出正确的类型,那么如果我们必须将该类型更改为另一个类型,我们就不会那么头痛.每个人都赢了. (6认同)
  • 在C中不需要转换malloc的结果,但是在C++中.而sizeof(char)总是1. (3认同)
  • @joe:sizeof(char)可能总是一个.但它仍然很好在代码中.它有各种各样的行为,例如你的意图的文档(并不像在运行时花费任何东西!). (2认同)
  • 另外使用 sizeof(*a) 和 sizeof(a->values[0]) 意味着您不会在代码中重复该类型。注意 sizeof 是编译时的,所以它是安全的。 (2认同)

Joh*_*ode 9

在C:

swc *s = malloc(sizeof *s); // assuming you're creating a single instance of swc
if (s)
{
  s->offset = malloc(sizeof *(s->offset) * number_of_offset_elements);
  s->values = malloc(sizeof *(s->values) * number_of_value_elements);
}
Run Code Online (Sandbox Code Playgroud)

在C++中:

try
{
  swc *s = new swc;
  s->offset = new short[number_of_offset_elements];
  s->values = new char[number_of_value_elements];
}
catch(...)
{
   ...
}
Run Code Online (Sandbox Code Playgroud)

请注意,在C++中,您可能最好使用向量而不是动态分配的缓冲区:

struct swc 
{
  std::vector<short> offset;
  std::vector<char> values;
};

swc *a = new swc;
Run Code Online (Sandbox Code Playgroud)

问题:值应该是单个字符数组还是字符串数组?这会改变一些事情.

编辑

我想的越多,我对C++答案的满意度就越低; 在C++中执行此类操作的正确方法(假设您需要动态分配的缓冲区而不是矢量,您可能不需要)是为结构类型中的构造函数执行偏移量和值的内存分配,并且析构函数在结构实例被销毁时(通过a delete或通过超出范围)释放这些元素.

struct swc
{
  swc(size_t numOffset = SOME_DEFAULT_VALUE, 
      size_t numValues = SOME_OTHER_DEFAULT_VALUE)
  {
    m_offset = new short[numOffset];
    m_values = new char[numValues];
  }

  ~swc()
  {
    delete[] m_offset;
    delete[] m_values;
  }

  short *m_offset;
  char  *m_values;
};

void foo(void)
{
  swc *a = new swc(10,20); // m_offset and m_values allocated as 
                           // part of the constructor
  swc b;                   // uses default sizes for m_offset and m_values
  ...
  a->m_offset[0] = 1;
  a->m_values[0] = 'a';
  b.m_offset[0] = 2;
  b.m_values[0] = 'b';
  ...
  delete a; // handles freeing m_offset and m_values
            // b's members are deallocated when it goes out of scope
}
Run Code Online (Sandbox Code Playgroud)


Joe*_*oeG 5

你必须单独做。首先分配结构体,然后分配数组的内存。

在C中:

swc *pSwc = malloc(sizeof(swc));
pSwc->offset = malloc(sizeof(short)*offsetArrayLength);
pSwc->values = malloc(valuesArrayLength);
Run Code Online (Sandbox Code Playgroud)

在 C++ 中,你不应该做这样的事情。


Mar*_*ork 5

在C中:

typedef struct
{
    short *offset;
    char  *values;
} swc;

/// Pre-Condition:  None
/// Post-Condition: On failure will return NULL.
///                 On Success a valid pointer is returned where
///                 offset[0-n) and values[0-n) are legally de-refrancable.
///                 Ownership of this memory is returned to the caller who
///                 is responsible for destroying it via destroy_swc()
swc *create_swc(unsigned int size)
{
    swc *data    = (swc*)  malloc(sizeof(swc));
    if (data)
    {
        data->offset = (short*)malloc(sizeof(short)*n);
        data->values = (char*) malloc(sizeof(char) *n);
    }
    if ((data != NULL) && (size != 0) && ((data->offset == NULL) || (data->values == NULL)))
    {
        // Partially created object is dangerous and of no use.
        destroy_swc(data);
        data = NULL;
    }
    return data;
}
void destroy_swc(swc* data)
{
    free(data->offset);
    free(data->values);
    free(data);
}
Run Code Online (Sandbox Code Playgroud)

在 C++ 中

struct swc
{
    std::vector<short>   offset;
    std::vector<char>    values;
    swc(unsigned int size)
        :offset(size)
        ,values(size)
    {}
};
Run Code Online (Sandbox Code Playgroud)


Ash*_*ish 1

使用malloc函数或calloc动态分配内存。并在谷歌上搜索以获取示例。

The calloc function initializes allocated memory to zero.
Run Code Online (Sandbox Code Playgroud)