2010-10-01 31 views
4

我想移動一大塊我記憶中的數據。不幸的是,這些數據被保存爲一個數組,我不能改變它。我不能使用循環數組,因爲同樣的內存也被一些我不想改變的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調用,但不是每次!所以它可能會更快,不是嗎?

回答

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} 

X表示不確定。

+0

非常感謝您的回答和你的解釋!即使這對我來說是個壞消息:( – 2010-10-01 18:49:21

3

爲什麼不簡單地複製一個一個的元素?

#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;