I would like to add an element at the end of the array. LENGTH(a) is a marco which means the size of the array a
. Initial value of the array is {1}. I would like to add all even-number into array.So,the result I want is array = {1,0,2,4},but the result is as the picture shows.
The code is as follows:
#include <stdio.h>
#include <stdlib.h>
#define LENGTH(a) (sizeof(a) / sizeof(*a))
void insert(int *, int);
void main(){
int size = 1;
int * array = (int*)malloc(size * sizeof(int));
array[0] = 1;
int i;
int value = 0;
for(i = 0; i < 5; i++){
if (i%2 == 0){
insert(array, i);
}
}
for(i = 0; i < LENGTH(array); i++) {
printf("array[%d] = %d\n", i, array[i]);
}
}
void insert(int *array, int a){
array = realloc(array, (LENGTH(array)+1)*sizeof(int));
printf("length = %d\n", LENGTH(array));
array[LENGTH(array)] = a;
}
I'd like to know why this occurs and how to solve it.