Using what I have learned here: How to use realloc in a function in C, I wrote this program.
int data_length; // Keeps track of length of the dynamic array.
int n; // Keeps track of the number of elements in dynamic array.
void add(int x, int data[], int** test)
{
n++;
if (n > data_length)
{
data_length++;
*test = realloc(*test, data_length * sizeof (int));
}
data[n-1] = x;
}
int main(void)
{
int *data = malloc(2 * sizeof *data);
data_length = 2; // Set the initial values.
n = 0;
add(0,data,&data);
add(1,data,&data);
add(2,data,&data);
return 0;
}
The goal of the program is to have a dynamic array data
that I can keep adding values to. When I try to add a value to data
, if it is full, the length of the array is increased by using realloc.
Question
This program compiles and does not crash when run. However, printing out data[0]
,data[1]
,data[2]
gives 0,1,0
. The number 2
was not added to the array.
Is this due to my wrong use of realloc
?
Additional Info
This program will be used later on with a varying number of "add" and possibly a "remove" function. Also, I know realloc
should be checked to see if it failed (is NULL
) but that has been left out here for simplicity.
I am still learning and experimenting with C. Thanks for your patience.