[C] Problem with pointers and arrays
Hi everyone! I wrote this code to calculate a polynomy's derivative:
[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<N; 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!!!