user2737810
user2737810

Reputation: 21

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.

Upvotes: 0

Views: 103

Answers (3)

chux
chux

Reputation: 153478

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();

Upvotes: 1

Dwayne Towell
Dwayne Towell

Reputation: 8583

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

Upvotes: 3

John Zwinck
John Zwinck

Reputation: 249153

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

Upvotes: 1

Related Questions