如何创建一个结构在C两个可变大小的数组 [英] How to create a structure with two variable sized arrays in C

查看:130
本文介绍了如何创建一个结构在C两个可变大小的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个轻量级的序列化功能,需要包括在该两个可变大小的数组。

I am writing a light weight serialization function and need to include two variable sized arrays within this.


  • 我应该如何跟踪每个?
  • 的大小
  • 我应该如何定义结构?

  • 我要对所有这一切错了吗?

编辑:其结果必然是一个连续的内存块

the result must be a contiguous block of memory

推荐答案

由于数据应该是在内存中连续有必要的malloc大小合适的内存块,并对其进行管理的手动内容的更多或更少。你可能最好创建一个包含做内存管理和提供访问该结构的动态成员静态的信息和相关的管理功能结构:

Since the data should be continuous in memory it is necessary to malloc a chunk of memory of the right size and manage it's contents more or less manually. You probably best create a struct that contains the "static" information and related management functions that do the memory management and give access to the "dynamic" members of the struct:

typedef struct _serial {
  size_t sz_a;
  size_t sz_b;
  char data[1]; // "dummy" array as pointer to space at end of the struct
} serial;

serial* malloc_serial(size_t a, size_t b) {
  serial *result;
  // malloc more memory than just sizeof(serial), so that there
  // is enough space "in" the data member for both of the variable arrays
  result = malloc(sizeof(serial) - 1 + a + b);
  if (result) {
    result->sz_a = a;
    result->sz_b = b;
  }
  return result;
}

// access the "arrays" in the struct:

char* access_a(serial *s) {
  return &s->data[0];
}

char* access_b(serial *s) {
  return &s->data[s->sz_a];
}

然后,你可以做这样的事情:

Then you could do things like this:

  serial *s = ...;
  memcpy(access_a(s), "hallo", 6);
  access_a(s)[1] = 'e';

另外请注意,你不能只分配一个串口到另外一个,你需要确保的大小兼容,并手动复制数据。

Also note that you can't just assign one serial to another one, you need to make sure that the sizes are compatible and copy the data manually.

这篇关于如何创建一个结构在C两个可变大小的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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