题
我想移动记忆中的大量数据。不幸的是,这些数据被保存为数组,我无法更改它。我不能使用圆形阵列,因为我不想更改的几种fortran方法也使用了相同的内存。最重要的是,在机芯之间非常频繁地访问阵列。所以我可以做到这一点:
int *array = (int*) malloc(sizeof(int)*5);
int *array2=NULL;
//Now i want to move my data one step to the left
array=(int*) realloc(array,6);
array2=array+1;
memmove(array,array2,5*sizeof(int));
array=(int*) realloc(array,5);
这应该很好,但是看起来很浪费;)。如果我能告诉我的编译器在收缩阵列的左侧取出数据,我的数据会在内存中蔓延,但是我不必进行任何复制。像这样:
int *array = (int*) malloc(sizeof(int)*5);
//Now i want to move my data one step to the left
array=(int*) realloc(array,6);
array=(int*) realloc_using_right_part_of_the_array(array,5);
所以我基本上想完成一个指针 array+1
, ,它的四个字节释放了。我玩了 free()
和 malloc()
但这并没有起作用...我知道Realloc也可能导致一个纪念电话,但并非每次!所以它可能更快,不是吗?
解决方案
否。没有办法回馈您分配的内存的下部。另外,由于您要复制不确定的内存,因此您的原始代码是错误的。
int *array = (int*) malloc(sizeof(int)*5);
// Fill memory:
// array - {'J', 'o', h', 'n', '\0'};
int *array2=NULL;
//Now i want to move my data one step to the left
array=(int*) realloc(array,6);
// array - {'J', 'o', h', 'n', '\0', X};
array2=array+1;
// array2 pointer to 'o of array.
memmove(array,array2,5*sizeof(int));
// This copies the indeterminate x:
// array - {'o', h', 'n', '\0', X, X}
array=(int*) realloc(array,5);
// array - {'o', h', 'n', '\0', X}
x表示不确定。
其他提示
您为什么不简单地将元素一一复制?
#define NELEMS 5
for (i = 0; i < NELEMS - 1; i++) {
array[i] = array[i + 1];
}
array[NELEMS - 1] = 0;
或者,使用 memmove
就像您一直在做的一样,但没有搬迁
#define NELEMS 5
memmove(array, array + 1, (NELEMS - 1) * sizeof *array);
array[NELEMS - 1] = 0;
不隶属于 StackOverflow