Like BLUEPIXY said, pass a double pointer or if you don't want to, better this:
float *double_array_size(float *array, int *size) {
float *temp = NULL;
int i;
temp = (float *) malloc(*size * 2 * sizeof(float));
for (i = 0; i < *size; i++) {
temp[i] = array[i];
}
*size *= 2;
free(array);
return temp;
}
and to increase the performance of you code, do not use a for loop, use memcpy instead:
temp = (float *) malloc(*size * 2 * sizeof(float));
memcpy(temp, array, sizeof *array * *size);
You should always check the return value of malloc and friends. They might return NULL and depending on your code, you might have to react to this if you don't want your code to crash.
Another thing: if you are using C only, do not cast malloc and I suggest to use sizeof *var instead of sizeof(float) because you are hardcoding the type. Let's say that you have to change the type of the array. If you hardcore your types, you have to change the types everywhere, otherwise only in the declarations, much less work and fewer errors.
Sometimes you need more or less the same code for different types. Luckily in C++ you have templates, in C you have to use Macros, if you don't want to repeat basically the same code over and over, for example:
#define DOUBLE_ARRAY_SIZE(type) \
type *double_array_size_ ##type (type *array, size_t *size) {\
type *temp; \
temp = malloc(*size * 2 * sizeof *array);\
if(temp == NULL)\
return NULL;\
memcpy(temp, array, sizeof *array * *size);\
*size *= 2;\
free(array);\
return temp;\
}
And instead of writing the same code with different types over and over, you can do
DOUBLE_ARRAY_SIZE(int)
DOUBLE_ARRAY_SIZE(double)
DOUBLE_ARRAY_SIZE(record_t)
void foo()
{
int *ints = malloc(...);
record_t *recs = malloc(...);
...
new_ints = double_array_size_int(ints, ints_size);
new_recs = double_array_size_record_t(recs, recs_size);
....
}
I know that a lot of people will say do not use macros, they're evil and they are kind of true, but using them wisely may help you more thank you think. One of the reason you should try to hardcore the datatype as less as possible.
// edit my macro snippet, chux's suggestion with size_t
void f(int x) {x = 5;} int main() {int i = 7; f(i); printf("%d\n", i); return 0;}to print?float **array.free()like that, the context where you callfree()seems wrong and dangerous to me.double_array_size()is also changing the pointer itself.