I've got a problem with dynamic array. I have to write a program which adds a character to dynamic array starting with 0 elements going to 10. I mustn't use realloc and I have to free the array each time.
#include <stdio.h>
#include <stdlib.h>
void add(int **ptab, int n, int new_elem)
{
int *tab2, y;
tab2 = malloc(n * sizeof(int));
for(y = 0; y < n; y++)
{
tab2[y] = (*ptab)[y];
}
*ptab = tab2;
(*ptab)[n] = new_elem;
free(ptab);
}
main()
{
int *ptab, i, x;
*ptab = NULL;
for(i = 0; i < 10; i++)
{
scanf("%d", &x);
add(&ptab, i, x);
}
for(i = 0; i < 10; i++)
{
printf("%d", ptab[i]);
}
}
*ptab = NULL;-->ptab = NULL;,tab2=malloc (n * sizeof(int));-->tab2=malloc ((n+1) * sizeof(int));