我有一个关于练习的问题,这可以解释malloc是如何工作的。
首先,我们已经给出了标题:
struct cell_m
{
unsigned int magicnumber ;
struct cell_m *next ;
void *userspacestart ;
void *userspacestop ;
};
typedef struct cell_m *liste_t ;
正如您所看到的,我只有一个下一个指针,因此它是一个简单的链式列表。
我应该编写一个函数来在cell_m
的{{1}}内插入liste_t
。
有一个条件,我们要插入的cell_m的大小必须小于我们当前所在的大小。 这是我的函数代码:
cell_m
一点解释:我试着保持我在列表中的最后位置,所以我创建了一个" old_list "变量来保持它。 起初,我试图看看我是否可以直接在列表的开头插入我的单元格。我不完全确定放在这里的内容所以我现在发表评论。
然后,如果它不能在开始时插入它,我将前进到我的列表并尝试插入元素。 (然后,再次,不完全确定插入的代码是否正确)
这有什么用,或者我对这段代码完全错了吗?
答案 0 :(得分:-1)
假设第一个指针指向指向列表的指针,第二个参数是指向要插入的新元素的指针,则没有理由对malloc()进行任何操作。您只需要在列表中找到要插入的位置。
struct cell_m {
unsigned int magicnumber ;
struct cell_m *next ;
char *userspacestart ; // character pointers allow pointer arithmetic
char *userspacestop ;
};
// typedefs only exist to confuse you
// typedef struct cell_m *liste_t ;
void insert(struct cell_m **head, struct cell_m *this)
{
for ( ;*head != NULL; head = &(*head)->next) {
if (*head)->userspacestop - (*head)->userspacestart
< this->userspacestop - this->userspacestart) break;
}
this->next = *head;
*head = this;
}
您当然可以使用void *
指针执行相同的操作,但是您需要对char*
(或其他一些粒度)进行大量强制转换才能使其正常工作。