Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/magento/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C中,如何将不同数据类型的多个数据插入并检索回一个数组中?_C_Arrays_Structure - Fatal编程技术网

在C中,如何将不同数据类型的多个数据插入并检索回一个数组中?

在C中,如何将不同数据类型的多个数据插入并检索回一个数组中?,c,arrays,structure,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; 这是行不通的,我要展示的只是回答你的问题,但这是一种错误的方式

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

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;
struct块
{
大小;
下一个街区;
t_block prev;
无整数;
字符数据[1];//大小;

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

@KarolyHorvath:我知道,我也提到过。请继续,并指明正确的方向。@KarolyHorvath:啊..现在我明白我完全搞砸了。修复了它。忘了我创建了一个字符数组:p