# pointer and function

Hello,
I’ve a function which complete an array of double. When I print the array in the function it seems to be complete (i’ve number in the array) but when i try to print the array after the function, the array is only full of zero.

``````
int rot_321(int[],double*);

void main void{
int angles [3]={45,0,0};
double rotmat[3][3];

rot_321(angles,(double*)rotmat);

for(i=0;i<9;i++)
printf("%d:%lf\n",i,*(rotmat+i*sizeof(double)));
}

int rot_321(int angles[3],double* rotmat)
{
double phi,theta,psi;
int i;

phi   = angles[0]*M_PI/180;
theta = angles[1]*M_PI/180;
psi   = angles[2]*M_PI/180;

*rotmat=cos(psi)*cos(theta);
*(rotmat+1*sizeof(double))=-1*sin(psi)*cos(phi)+cos(psi)*sin(theta)*sin(phi);
*(rotmat+2*sizeof(double))=sin(psi)*sin(phi)+cos(psi)*cos(phi)*sin(theta);
*(rotmat+3*sizeof(double))=sin(psi)*cos(theta);
*(rotmat+4*sizeof(double))=cos(psi)*cos(phi)+sin(phi)*sin(theta)*sin(psi);
*(rotmat+5*sizeof(double))=-cos(psi)*sin(phi)+sin(theta)*sin(psi)*cos(phi);
*(rotmat+6*sizeof(double))=-sin(theta);
*(rotmat+7*sizeof(double))=cos(theta)*sin(phi);
*(rotmat+8*sizeof(double))=cos(theta)*cos(phi);

for(i=0;i<9;i++)
printf("%d:%lf\n",i,*(rotmat+i*sizeof(double)));
return 1;
}
``````

as I said when I print at the end of the fonction, the array is correctly completed. But when I print again in the main function juste after the call of “rot_321” the array is just full of zero. Can someone explain me why.
Thanks.

That is because of the way you are using the rotmat pointer:

It’s a pointer to a double, but you multiply the offset by the size of the data it points to. The C compiler knows its a pointer to a double hence when doing rotmat+1 it will actually add 4 to rotmat and not rotmat.

You are lucky (or unlucky) the code doesn’t crash because rot_321 write past the size of the rotmat array.

The make the code more readable instead of passing a pointer to a double pass an array of type[3][3] or a pointer to an array of 3 double.

voit rot_321(nt angles[3],double*rotmat[3])
{
rotma[0][0] =cos(psi)cos(theta);
rotmat[0][1] =-1
sin(psi)*cos(phi)+cos(psi)*sin(theta)*sin(phi);