[CODE]
typedef int *poly;
typedef poly *der;
der derivative(poly P, int N, int k);
int calcolaDerivata(int coeff, int grado);
der derivative(poly P, int N, int k)
{
int i, j, f;
der d;
poly p2;
poly pp;
d = calloc(N, sizeof(poly));
p2 = calloc(k+1, sizeof(int));
for( i=0; i
p2 = calloc(k+1, sizeof(int));
for( j=0; j<=k; j++ )
{
p2[j] = calcolaDerivata(P[j], j+1);
printf("%d: %d -- %d\n",j,P[j],p2[j]);
}
k -= 1;
[B] d[i] = p2;[/B]
pp=d[i];
printf("i: %d\nd: %d %d %d %d\n",i, pp[0], pp[1], pp[2], pp[3] );
getch();
for( f=0; f<=k; f++ )
P[f]=p2[f+1];
//free(p2);
}
pp=d[0];
printf("\n\nCycle:\n\ni: %d\nd: %d %d %d %d",i, pp[0], pp[1], pp[2], pp[3] );
getch();
return d;
}
int calcolaDerivata(int coeff, int grado)
{
if( grado == 1 )
return 0;
else
return coeff*(grado-1);
}
[/CODE]
I don't want to talk about the algorithm, I just want to understand why the bolded code (d[i] = p2) every time copies the value of p2 into EVERY elements of d.
In other words:
1 iteration --> d[0] = p2 OK (at the end of the cycle, I of course recalculate p2 value)
2 iteration --> d[1] = p2 and I have d[0] AND d[1] with the same value!!! Why the assignment of d[1] changes the value of d[0] too???
Of course, each iteration copies the last value in EVERY elements of d.
Could you please help me? Thanks a lot!!!
marco_brovelliPosted Jan 7, 2011, 4:48 AM
I solved this one, commenting ther free(p2) line.
Sam HobbsPosted Jan 7, 2011, 4:45 AM
In the line that has "d[i] = p2;" you do not have an index so I assume p2 has the address; the return value of calloc. I assume that is not what you want but I am not sure. When you do a calculation for p2, you have an index as in "p2[j]".
It is difficult for me to know what it is that you need to do since the code you posted is C code written in a manner that is intended to be difficult to understand. On top of that, I do not know what the code is supposed to be doing.