簡體   English   中英

為C中的數組動態分配內存

[英]Dynamically allocate memory for array in C

我已將內存分配給數組(使用malloc ),但是如果需要更多空間怎么辦,是否可以稍后在程序中擴展數組? 還是創建一個新數組並使第一個數組中的最后一個元素指向新數組?
我知道realloc會更容易使用,但是我試圖僅使用malloc來做到這一點。

通用算法是

allocate array of 100
while more input
    if no-room-in-array
        allocate another array 100 bigger than the current array
        copy values from current array into newly created array
        free(current array)
        current array = newly created array (the one you copied into)
    // now there will be room, so
    put input in array

是的,您可以使用realloc() 但是,在將返回值分配給原始指針之前,請務必檢查其返回值。 看到這里: https : //stackoverflow.com/a/1986572/4323

錯誤的大小傳遞給malloc()

代碼應該傳遞n * sizeof(int)而不是傳遞n個字節。

// int *array1=(int *)malloc(100);
int *array1 = malloc(100 * sizeof *array1);

// int *newArray=(int *)malloc(size+100);
int *newArray =  malloc((size+100) * szeof *newArray);

其他想法包括

1)無需投放

    int *array1 = (int *) malloc(...;
    int *array1 = malloc(...);

2)用memcpy()簡化

    // for(i=0; i<size; i++) newArray[i]=array1[i];
    memcpy(newArray, array, size * sizeof *newArray);

3)確保free()

4) new是一個C ++運算符,這是C,使用malloc()

5)使用size_t而不是int作為size

6)指數增長,而不是線性增長

// int *newArray=(int *)malloc(size+100);
size_t newsize = size*3/2;
int *newArray = malloc(newsize);

7)檢查malloc()失敗

int *newArray = malloc(newsize);
if (newArray == NULL && newsize > 0) Handle_Failure();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM