我想移動一大塊我記憶中的數據。不幸的是,這些數據被保存爲一個數組,我不能改變它。我不能使用循環數組,因爲同樣的內存也被一些我不想改變的fortran方法所使用。最重要的是,陣列在運動之間非常頻繁地被訪問。所以我可以這樣做:可以realloc收縮左側的數組(僅限C)?
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
,還剩它釋放的4個字節。我玩free()
和malloc()
,但它沒有工作... 我知道realloc也可能會導致memcpy調用,但不是每次!所以它可能會更快,不是嗎?
非常感謝您的回答和你的解釋!即使這對我來說是個壞消息:( – 2010-10-01 18:49:21