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.
3 Answers
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
2 Comments
Dwayne Towell
Don't change your question. If you need to add something add it.
user2737810
No it doesn't, my implementation of current array = newly created array (the one you copied into) is wrong. Not really sure why
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
3 Comments
user2737810
Like I said I cant use realloc
John Zwinck
@user2737810: what platform are you on that you can't use realloc()?
user2737810
The program specs dont allow realloc
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();
newArray=new array(array1)You're using malloc, so I'm not sure what that is meant to be#include <stdlib.h>