在指针指向的地址处创建结构 [英] Creating a struct at address pointed by pointer

查看:72
本文介绍了在指针指向的地址处创建结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个unsigned char* head指向内存中的某个addess,现在我必须创建一个我已经从该指针的位置开始声明的typedef结构...我对如何做到这一点感到困惑!

I have a unsigned char* head that is pointing to a certain addess in memory and now I have to create a typedef struct that I've declared starting at the location of that pointer...I am confused on how to do that!

这是typedef的声明

Here is the declaration of the typedef

 typedef struct {
    struct block *next;
    struct block *prev;
    int size;
    unsigned char *buffer;
} block;

我的工作涉及实现malloc,所以我不能使用malloc.一个块是free_list的一部分,它包含我程序堆中所有空闲内存块的所有块.因此,指向上一个和下一个空闲内存块的上一个和下一个指针.

My assignment involves implementing malloc, so I can't use malloc. A block is part of a free_list which contains all chunks of free memory blocks that I have in my program heap. Hence, the previous and next pointers that point to the previous and next free blocks of memory.

Head指向free_list的开头.当我不得不拆分时,说第一块空闲内存可以满足需要较少空间的malloc()请求,那么我需要移动该头并在那里创建一个新的块结构.

Head points to the start of the free_list. When I have to split say the first block of free memory to satisfy a malloc() request that needs less space then that free block has I need to move my head and create a new block struct there.

希望这是有道理的.如果不是,则分配看起来像

Hope this makes sense. If not, the assignment looks something like this

推荐答案

您的结构没有标签,因此您需要给它一个标签,使其指向自身:

Your struct has no tag, so you need to give it one in order for it to point to itself:

 typedef struct block {
    struct block *next;
    struct block *prev;
    int size;
    unsigned char *buffer;
} block;

如果使用的是C99,则可以在必要时直接在head处初始化内存,而无需声明临时的struct block:

If you're using C99 you can initialise the memory at head directly, if necessary, without declaring a temporary struct block:

*(block *)head = (block){NULL, NULL, 0, NULL};

现在,只要正确投放,您在地址head上就有一个struct block.

You now have a struct block at the address head, as long as you cast it properly.

例如

((block *)head)->size = 5;

或者您为其分配强制转换指针:

Or you assign a cast pointer to it:

block *p = (block *)head;
p->size = 5;

这篇关于在指针指向的地址处创建结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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