Skip to main content
GameDev.net gamedev.net
🔒 Locked

C problems

Started by fredrikhcs Feb 14, 2009 at 4:04 AM 1 replies 800+ views
Original Post
fredrikhcs
fredrikhcs
These two examples are very confusing to me. the function 'normcrossprod' has return value void, and it doesn't have reference parameters, so how can it change the variable 'norm'? Same thing with the function 'normalize'. Sidenote: even if 'normalize' returned a value, it would only be the value stored inside v[2], not the v array itself, right? The book chapter: http://www.glprogramming.com/red/chapter02.html Example 2-14 : Generating Normal Vectors for a Surface

GLfloat d1[3], d2[3], norm[3];    
for (j = 0; j < 3; j++) {    
   d1[j] = vdata[tindices[0]][j] - vdata[tindices[1]][j];    
   d2[j] = vdata[tindices[1]][j] - vdata[tindices[2]][j];    
}
normcrossprod(d1, d2, norm); 
glNormal3fv(norm);



Example 2-15 : Calculating the Normalized Cross Product of Two Vectors
void normalize(float v[3]) {    
   GLfloat d = sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]); 
   if (d == 0.0) {
      error("zero length vector");    
      return;
   }
   v[0] /= d; v[1] /= d; v[2] /= d; 
}

void normcrossprod(float v1[3], float v2[3], float out[3]) 
{ 
   GLint i, j; 
   GLfloat length;

   out[0] = v1[1]*v2[2] - v1[2]*v2[1]; 
   out[1] = v1[2]*v2[0] - v1[0]*v2[2]; 
   out[2] = v1[0]*v2[1] - v1[1]*v2[0]; 
   normalize(out); 
}


[Edited by - fredrikhcs on February 14, 2009 6:23:34 AM]
DevFred
DevFred
In C, everything is passed by value.

In C, it is impossible to pass an array.

In C, what looks like passing an array is actually passing a pointer to the first element of the array.

That's why your functions have visible side-effects. They manipulate the original data.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.