Initializing C-style array for use in Objective-C class

Discussion in 'Mac Programming' started by Thethuthinang, Jan 28, 2012.

  1. macrumors member

    Joined:
    Jan 3, 2011
    #1
    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?
     
  2. macrumors 68000

    Sydde

    Joined:
    Aug 17, 2009
    #2
    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).
     
  3. macrumors 603

    Joined:
    Aug 9, 2009
    #3
    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.
     
  4. thread starter macrumors member

    Joined:
    Jan 3, 2011

Share This Page