c - Pointer to struct elements -


i need write function sums monoms same power, monoms defined following struct:

typedef struct monom {     int coefficient;      int power; }monom; 

and function wrote job is:

int summonomswithsamepower(monom** polynomial, int size) {         int i, powerindex = 0;          (i = 0; < size; i++)         {             if ((polynomial[powerindex])->power == (polynomial[i])->power)                 {                         if (powerindex != i)                                 (polynomial[powerindex])->coefficient += (polynomial[i])->coefficient;                  }                  else                         powerindex++;         }          powerindex++;         *polynomial = (monom*)realloc(polynomial, powerindex);         return powerindex; } 

which being called following call:

*polysize = summonomswithsamepower(&polynomial, logsize); 

polynomial array being sent function sorted array of monoms (sorted ascending powers).

my problem on 7th line of summonomswithsamepower() function crashes since can't see elements in array following way. when put elements of array in watch list in debugger can't see them using polynomial[i], if use (polynomial[0]+i) can see them clearly.

what going on here?

i assume outside summonomswithsamepower() have allocated polynomial polynomial = malloc( size * sizeof(monom) ); (everything else wouldn't consistant realloc()). have array of monoms , memory location of polynomial[1] polynomial[0] + sizeof(monom) bytes.

but @ polynomial in summonomswithsamepower() in following paragraph rename ppoly (pointer polynomial) avoid confusing original array: here monom **, ppoly[1] addresses sizeof(monom *) bytes @ memory location ppoly[0] + sizeof(monom *) , interpretes them pointer monom structure. have array of structs, not array of pointers. replace expressions (*ppoly)[i].power (and others accordingly of course) , part work. way that's excactly difference of 2 debugger statements have mentioned.

besides, @ comments concerning use of powerindex


Comments