Otwrate
Otwrate

Reputation: 27

dynamic array in C resizing

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]);
    }
}

Upvotes: 0

Views: 118

Answers (1)

Useless
Useless

Reputation: 67812

*ptab=tab2;   
(*ptab)[n]=new_elem;
free(ptab);

should be

free(*ptab);
*ptab=tab2;   
(*ptab)[n]=new_elem;

Currently, you're overwriting the old array pointer before freeing it, so you no longer know what you're supposed to free.

Upvotes: 3

Related Questions