I have a CGFloat pointer in my header that is used to point at a CGFloat array. I declare it like that: CGFloat* pointer;. In the initialization I try to set the pointer using this code:
CGFloat newArray[2] = {
0.0f, 1.0f,
};
pointer = newArray;
This “actually” works. I don’t get any compiler errors and stuff. When i print the second value of the array right after setting the pointer with this code: printf("%f", pointer[1]);
I get the right result (1.000000). However, when I print the second value of the array in the method called next i get 0.000000 which means that the pointer doesn’t point at the array anymore.
I’ve got two questions. How do I fix this problem and why does the pointer work right after setting it but “forgets” its value again?
Array indices start at 0.
pointer[1]prints the second element in the array, not the first.pointer[2]is off the end of the array.Note that if you try to pass
newArraysomewhere with the intention of using it later, it’ll be badness.newArrayis on the stack and will be destroyed when the scope is destroyed.If you want a function that returns an array of two floats, you’d do:
Just make sure and call
freeon that return value later. Note that it is exceedingly rare to allocate something so small. Typically, it’ll be a structure that is returned directly. SeeCGPoint,CGRect,NSRange, etc….