简体   繁体   English

如何为具有数组的结构分配 memory?

[英]How do I allocate memory for a struct with an array?

Suppose I have this struct representing a virtual machine.假设我有这个代表虚拟机的结构。 Please, check out my init() method.请检查我的init()方法。 In the init() method I am allocating some space in the heap for the state of my virtual machine.init()方法中,我在堆中为虚拟机的 state 分配一些空间。 But, something doesn't seem right.但是,似乎有些不对劲。 I am allocating space first for my state (struct), then for the RAM (array of type int), which is already inside of my struct.我首先为我的 state(结构)分配空间,然后为 RAM(int 类型的数组)分配空间,它已经在我的结构中。 Is it okay?可以吗? or I'm doing something wrong?或者我做错了什么?

My question is how do I property allocate memory for the array inside of struct in the heap.我的问题是如何为堆中结构内部的数组分配 memory 属性。

typedef struct {
    int* ram;
    int   pc;
} vm_t;

vm_t* init(int ram_size)
{
   vm_t* vm = (vm_t*)malloc(sizeof(vm_t));
   vm->ram = (int*)malloc(ram_size * sizeof(int));
   vm->pc = 0;
  
   return vm; 
}

I would do it a bit different way.我会以不同的方式来做。 Only one malloc and free needed.只需一个 malloc 并且免费。

typedef struct {
    size_t   pc;
    int   ram[];
} vm_t;

vm_t* init(size_t ram_size)
{
   vm_t *vm = malloc(sizeof(*vm) + ram_size * sizeof(vm -> ram[0]));
   if(vm)
    vm -> pc = 0;
  
   return vm; 
}

Some remarks: use size_t for sizes, always checks the result of malloc .一些评论:使用size_t作为尺寸,总是检查malloc的结果。 Use objects not types in the sizeof .sizeof中使用对象而不是类型。 When you change the type memory allocation will not have to be changed.当你改变memory的类型时,配置就不必改变了。

I do not know why RAM has int type but it does not matter in this question.我不知道为什么 RAM 有int类型,但在这个问题上并不重要。

EDIT.编辑。 How to access.如何访问。 Example how to read the ram示例如何读取ram

int read_RAM(vm_t *vm, size_t address)
{
    return vm -> ram[address];
}

int read_RAM1(vm_t *vm, size_t address)
{
    return *(vm -> ram + address);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM