Array Initialization in OF

Hi,
I want to create an array with 100 values and all values are set to one.

So I use this code in ::setup()

  
float sampleArray [] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};  

All numbers are set to one correctly (I check this using printf at the end of ::setup on sampleArray[0], sampleArray[99]).

After ::setup, the program enters ::update right?
In the first line of ::update I check the values of sampleArray again and now they contain these numbers:
sampleArray[0] gives 0.000000
sampleArray[1] gives 0.000000
sampleArray[10] gives 7271217323912344800000000000.0000000
sampleArray[99] gives 829.207397

How could the values of sampleArray have changed?!
I also declare sampleArray in my .h file as follows:

  
float sampleArray[];  

Hi,

I think the problem is you are declaring a new array in the setup method, which goes out of scope at the end of the function.

you could try this instead.

declare array in header as

  
float sampleArray[100];  

then in setup you can initialize the values

  
  
        for (int i = 0; i<100; i++)  
        {  
            sampleArray[i] = (float) i;  
        }  
  

this should work.

regards
david

1 Like

Thanks a lot David! That worked :slight_smile:
I’m sometimes confused as what needs to be put in the header files and what in the cpp files…

I would like to ask a similar question.

I would like to initialize an array of strings.

string myColors[] = {“lightpink” , “pink” , “crimson”};
or
string myColors[3] = {“lightpink” , “pink” , “crimson”};

The C++ documentation seems to suggest that this should work but I am not able to figure this one out.

Thanks for any help.
Stephan.

Stephan,

You can’t actually initialize an array like that unless it’s within a method:

  
  
void printStrings () {  
	string myColors[3] = {"lightpink" , "pink" , "crimson"};  
	printf("%s", myColors[0].c_str());  
}  

if you’re going to create the string array in a class, i.e:

  
#include <iostream>  
  
using namespace std;  
  
class stringer {  
	  
public:  
	string myColors[];  
	stringer();  
  
};  

then you need to initialize the members one at a time:

  
#include "stringer.h"  
  
stringer::stringer() {  
	myColors[0] = "lightpink";   
	myColors[1] = "pink";   
	myColors[2] = "crimson";  
};  

Thanks for your fast reply Joshua.

This would mean I am not able to have an array of strings globally available.

To initialize the members one at a time will be very labour-some for an array of 140 items.

Stephan.

use:
char *myColors[] = {“lightpink” , “pink” , “crimson”};
instead of:
string myColors[] = {“lightpink” , “pink” , “crimson”};

initializers only work with non-classes i guess.

best
joerg