c - 我们如何在 C 中的数组中插入和检索不同数据类型的多个数据?

标签 c arrays structure

我想向数组添加一个结构,并在需要时将数据返回到结构中。有什么方法可以做到这一点吗?

char Memory[20000];

struct block
{
    size_t size;
    t_block next;
    t_block prev;
    int free;
    char data[1];
    void *ptr;

};

struct block aaa;
Memory[0]=(char) a;

这行不通

最佳答案

我要展示的只是回答你的问题,但这是一种错误的做法。结构中的指针会使情况变得更糟,因为您无法像 C++ 中那样添加类似于赋值运算符的内容。 所以,你必须**非常非常**小心'ptr'指向的内存。

struct block
{
    size_t size;
    t_block next;
    t_block prev;
    int free;
    char data[1]; // <= does it make sense ?
    void *ptr;

};

char Memory[sizeof(struct block) * 1000]; // 1000 is some random number I have picked, but
                                          // you have to multiply it with sizeof(struct)
                                          // so as not to access memory out of array bounds
struct block aaa = {1, /* some thing */ , /* some thing*/, 0, /* some thing*/, /*some thing */};

char* mem_ptr = &Memory[0];
// Storing
memcpy(mem_ptr, &aaa, sizeof(struct block));
mem_ptr += sizeof(struct block);

// Accessing
char* acc_ptr = &Memory[0];
struct block* abb = acc_ptr;
int i = abb->size;

当您将“ptr”从数组中取出并取消引用它时(当然是在转换之后),请格外小心,以确保“ptr”所指向的内容是有效的。

关于c - 我们如何在 C 中的数组中插入和检索不同数据类型的多个数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26830587/

相关文章:

c - 指向结构的指针数组

C++ 类型转换损坏的结构

c++ - 未给出显式整数后缀时,参数 'typing' 的规则是什么?

c - Visual Studio 2013 C/C++ 调试器,让你调用一个函数并打印结果

c - 与 fgets() 相关的段错误 - C

php - in_array vs strpos 在 php 中的性能

c - tcp 聊天客户端中的同步

javascript - 遍历没有数组的 JSON 键对象

c++ - 编译器错误 : invalid conversion from 'int' to 'int*' [-fpermissive]|

c - C 中的结构体数组