realloc能否在左侧收缩我的阵列(仅限C)?

realloc能否在左侧收缩我的阵列(仅限C)?,c,realloc,shrink,C,Realloc,Shrink,我想移动内存中的一大块数据。不幸的是,此数据保存为数组,我无法更改它。我不能使用循环数组,因为我不想更改的两个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=

我想移动内存中的一大块数据。不幸的是,此数据保存为数组,我无法更改它。我不能使用循环数组,因为我不想更改的两个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);
基本上我想用一个指向数组+1的指针来结束,剩下的4个字节被释放。我玩了
free()
malloc()
,但没用。。。
我知道realloc也可能导致memcpy调用,但不是每次都是这样!所以它可以更快,不是吗?

不。没有办法返回分配的内存的较低部分。另外,您的原始代码是错误的,因为您正在复制不确定的内存

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;

非常感谢您的回答和解释!尽管这对我来说是个坏消息:(
#define NELEMS 5
memmove(array, array + 1, (NELEMS - 1) * sizeof *array);
array[NELEMS - 1] = 0;