Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Thethuthinang

macrumors member
Original poster
Jan 3, 2011
39
0
I have some arrays that I need to initialize and use repeatedly throughout a class. For example:

Code:
float cubeMaterialDiffusion[] = {0.3, 0.7, 0.3, 1.0};

For the appropriate scope I need to declare the pointer to the array in the interface. However, if I declare cubeMaterialDiffusion in the interface as:

Code:
float* cubeMaterialDiffusion;

then I know of no concise way to initialize the array. I could do:

Code:
cubeMaterialDiffusion = malloc(4*sizeof(float));
cubeMaterialDiffusion[0] = 0.3;
cubeMaterialDiffusion[1] = 0.7;
cubeMaterialDiffusion[2] = 0.3;
cubeMaterialDiffusion[3] = 1.0;

Is there a better way to do this?
 

Sydde

macrumors 68030
Aug 17, 2009
2,552
7,050
IOKWARDI
I have not tried this, not really my style, what happens if you declare the ivar
Code:
float cubeMaterialDiffusion[4];
does it allocated the space for your array within your object? If so, if you expect to use an array that will not vary in size, then you can provide the pointer using the address operator '&' (it seems like poor style to me, but that is just me).
 

chown33

Moderator
Staff member
Aug 9, 2009
10,764
8,463
A sea of green
Is the same cubeMaterialDiffusion array used for all instances of the class? If so, then use a static C array, defined outside the @interface. Put it in the @implementation file, and declare it as a static array:
Code:
static float cubeMaterialDiffusion[] = {0.3, 0.7, 0.3, 1.0};
If you don't know why I'm using static, you should look it up in a C reference.

You might want the const qualifier on there, too, assuming the array is read-only.


If you need a different cubeMaterialDiffusion array for each instance, then it's like Sydde showed:
Code:
@interface YourClassName : YourSuperClass
{
  float cubeMaterialDiffusion[4];
..etc..
@end
You don't get to use the concise initializer notation, so in your init method:
Code:
cubeMaterialDiffusion[0] = 0.3;
cubeMaterialDiffusion[1] = 0.7;
cubeMaterialDiffusion[2] = 0.3;
cubeMaterialDiffusion[3] = 1.0;
This is the same as every other use of an instance variable. You don't get concise initializers for any of them. The +alloc method guarantees that all ivars are zeroed. Any other initialization is your responsibility.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.