0

Im trying to make a function that adds one more element to my dynamic allocated array of struct but i cannot seem to make it work . This is a part of my code:

void add_vect(complex *vect,int n)
{   int i,pos;

    complex *nr;
    printf ("Please enter the number you want to add : ");
    nr=read_complex(nr);
    write_complex(nr);
    printf ("Please enter the position of the new number : ");
    scanf("%d",&pos);
    n++;
    vect=realloc(vect,n*sizeof(complex));
    write_vect(n);
}

Here I'm reading the new complex number im trying to add to my array and the position it'll be added but when I realloc my array and I make a test to see if my old elements are still there, apparently it changes my last element.

so if i read 3 complex numbers

1 +2i , 3+4i, 5+6i

and i print my vector everything seems okay, but after I call this function and print it again after the realloc it shows:

v[1] = 1+2i - this one is good,
v[2] = 3+4i - still good,
v[3] = 121213121 +6i - not good and
v[4] = -12312321 +231312i 

and I get that v[4] is like this because I did not modify it but why is v[3] affected by the realloc?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
N. Seba
  • 19
  • 3
  • 3
    You're effectively discarding the result of `realloc`. Remember, `vect` is a function parameter, which is basically just a local variable. In particular, the caller still sees the old value of `vect`, which is no longer valid. – Tom Karzes Dec 09 '17 at 16:51
  • Welcome to Stack Overflow. Please read the [About] and [Ask] pages soon, but even more importantly (and urgently), read about how to create an MCVE ([MCVE]). Remember that arrays are indexed from 0 in C, normally. Also, we need to see the calling code. And `write_vect()` can't write the vector because it isn't passed the new value. If you have a global variable called `vect`, it is unaffected by the changes in the local variable `vect`. There's also no reliable way for the calling code to access the updated `vect`. – Jonathan Leffler Dec 09 '17 at 16:52
  • (you can think `realloc` as a `malloc` for new area followed by `memcpy` and then `free` for the old area, then apply the duplicate) – Antti Haapala -- Слава Україні Dec 09 '17 at 19:04

0 Answers0