Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

about pointer in c

Here is a small function defined by a typedef "sphere":

sphere Make_eyeball (float *c, float r) {

sphere eyeball;

eyeball.center[0] = c[0];
eyeball.center[1] = c[1];
eyeball.center[2] = c[2];

eyeball.radius = r;
return eyeball;

}

Q: float *c given as a float pointer, why can the program just use C as an array?

1 Answer

Your code copies the values/data within the memory locations of c to those of eyeball.center. Two benefits of copying are that now the data for the center values are contiguous within the struct eyeball next to radius and independent of c. No matter what happens later to c, e.g. being changed or released, the values within your eyeball struct will remain unaffected.

Thanks for the reply. What you are saying is c works as pointer and the actual data aren't stored in c but eyeball center. My confusion is that isn't it necessary to declare c as an array first, or array of pointers?

(sry, didn't subscribe to this thread so missed your question)

The function takes in basically 4 numbers (ignore the fact that the first 3 are referenced by pointers) and outputs a struct. So this function is simply there to encapsulate the process of changing 4 arbitrary pieces of data into something that has semantic meanings. The usage of this function could be something like this:

float some_random_point_in_space[3] = {1.0, -2.5, 3.0};
float some_random_number = 1.2

sphere eyeball = Make_eyeball(some_random_point_in_space, some_random_number);
// Now you can use eyeball instead of 4 arbitrary numbers, knowing well what they actually mean.