Hi guys, I'm currently a bit confused about passing structs to functions with pointers. I'm writing some very simple mathematical vector code, but it's not working as I expected.

Below is the code from the vector. The function createVec3 returns a Vec3 with the specified arguments. addVec3 should take two vec3 structs, add their values together and return a new vec3. sclVec3 creates a new vec3 whose values are those of a passed argument vec3 times a double k. addToVec3 and sclToVec3 are similar, but should perform the operation on the first argument vector rather than creating a new one.

In my main file I haveCode:typedef struct s_vec3 { double e1; double e2; double e3; } vec3; vec3 createVec3(double a, double b, double c) { vec3 newVec3; newVec3.e1 = a; newVec3.e2 = b; newVec3.e3 = c; return newVec3; } vec3 addVec3(vec3 a, vec3 b) { vec3 newVec3; newVec3.e1 = a.e1+b.e1; newVec3.e2 = a.e2+b.e2; newVec3.e3 = a.e3+b.e3; return newVec3; } vec3 sclVec3(vec3 a, double k) { vec3 newVec3; newVec3.e1 = a.e1*k; newVec3.e2 = a.e2*k; newVec3.e3 = a.e3*k; return newVec3; } void addToVec3(vec3 * a, vec3 b) { a->e1 += b.e1; a->e2 += b.e2; a->e3 += b.e3; } void sclToVec3(vec3 * a, double k) { a->e1 *= k; a->e2 *= k; a->e3 *= k; }

Which produces the outputCode:vec3 a = createVec3(0.5, 0.6, 0.7); vec3 b = createVec3(-0.3, -0.4, -0.1); vec3 c = addVec3(a, b); printf("a (%f %f %f)\n", a.e1, a.e2, a.e3); printf("b (%f %f %f)\n", b.e1, b.e2, b.e3); printf("c (%f %f %f)\n\n", c.e1, c.e2, c.e3); addToVec3(&a, c); printf("a (%f %f %f)\n", a.e1, a.e2, a.e3); printf("b (%f %f %f)\n", b.e1, b.e2, b.e3); printf("c (%f %f %f)\n\n", c.e1, c.e2, c.e3); sclToVec3(&a, 3.0); printf("a (%f %f %f)\n", a.e1, a.e2, a.e3); printf("b (%f %f %f)\n", b.e1, b.e2, b.e3); printf("c (%f %f %f)\n\n", c.e1, c.e2, c.e3);

The main point here is that the line "a (0.000000 0.000000 0.000000)" is incorrect from the call to sclToVec3(), but the adding operations seem to work. Also, including the lineCode:a (0.500000 0.600000 0.700000) b (-0.300000 -0.400000 -0.100000) c (0.200000 0.200000 0.600000) a (0.700000 0.800000 1.300000) b (-0.300000 -0.400000 -0.100000) c (0.200000 0.200000 0.600000) a (0.000000 0.000000 0.000000) b (-0.300000 -0.400000 -0.100000) c (0.200000 0.200000 0.600000)

instead of vec3 c = addVec3(a, b); gives a compile error: invalid initializer, which doesn't happen with addVec(a, b).Code:vec3 c = sclVec3(a, 3.0);

Can anyone pinpoint what I'm doing wrong here? Can I treat structs this way, and am I using pointers correctly?

Sorry for the really long post, but I figured I should include everything.