可以realloc缩小左侧的数组(仅限C)吗?

Nil*_*s_M 4 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=array+1;
memmove(array,array2,5*sizeof(int));
array=(int*) realloc(array,5);
Run Code Online (Sandbox Code Playgroud)

这应该工作正常,但它看起来很浪费;).如果我可以告诉我的编译器拿走缩小数组左侧的数据,我的数据会在内存中蔓延,但我不需要进行任何复制.像这样:

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);
Run Code Online (Sandbox Code Playgroud)

所以基本上我想用指针完成,array+1剩下的4个字节被释放.我打得四处free()malloc(),但它没有工作......我知道,realloc的还可能会导致的memcpy调用,但不是每次!所以它可能会更快,不是吗?

Mat*_*hen 5

不可以.无法回放您分配的内存的下半部分.此外,您的原始代码是错误的,因为您正在复制不确定的内存.

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}
Run Code Online (Sandbox Code Playgroud)

X意味着不确定.