简体   繁体   中英

Dynamically allocate memory for array in C

I allocated memory to an array (using malloc ) but what if it needs more space, is it possible to expand the array later in the program? Or maybe create a new array and have the last element in the first array point to the new array?
I know that realloc would be much easier to use but I am trying to do this only using malloc .

The general algorithm is

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

Yes, you can use realloc() . Be careful to check the return value before you assign it to the original pointer though. See here: https://stackoverflow.com/a/1986572/4323

Wrong size passed to malloc() .

Rather than passing n bytes, code should pass n * sizeof(int) .

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

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

Other ideas include

1) No need to cast

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

2) Simplify with memcpy()

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

3) Be sure to free()

4) new is a C++ operator, this is C, use malloc() .

5) Use size_t rather than int for size .

6) Grow exponentially, rather than linearly

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

7) Check for malloc() failure

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM