简体   繁体   English

如何使用带有指针的指针的记忆?

[英]How to use memmove with pointer of pointer?

I have the following struct in C: 我在C中具有以下结构:

typedef struct {
double value;
char* name;
} COMPONENT;

And I have the following vector of pointers: 而且我有以下指针向量:

COMPONENT **list = malloc(sizeof(COMPONENT*)*100);

This list contains only 10 pointers of COMPONENT struct even allocated for 100 elements, ok. 该列表仅包含10个COMPONENT结构的指针,甚至可以分配给100个元素。 Now, I want to insert at the first position a new COMPONENT using the memmove: 现在,我想使用记忆棒在第一个位置插入一个新的COMPONENT:

memmove(list+sizeof(COMPONENT*), list, sizeof(COMPONENT*)*10);
list[0] = new_element_ptr;

But this operation is not working =[. 但是此操作不起作用= [。 I'm losing all other references (list[1], list[2] and so on...). 我正在丢失所有其他引用(列表[1],列表[2]等...)。 Is this differents because it is a struct and my vector have only pointers? 因为它是一个结构并且我的向量只有指针,所以这有区别吗?

This is what you are looking for: 这是您要寻找的:

memmove(list + 1, list, sizeof(list[0]) * 10);

When adding to pointers, you are not adding byte offsets, you are adding number of elements. 在添加指针时,您未添加字节偏移,而是添加了元素数量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM