Problems with arrays in Draw()

I'm having this silly problem with an array; I declare it globally, I define the size and contents in Setup(), and when I try to access its values in Draw() I get a nullpointerexception. Any ideas what I'm doing wrong?

Here is a part of the code, that reproduces the error:

float grid[];
int times = 16;
void setup(){
  size (512,512);
  background(0);
  float grid[] = new float[(width+height)/times];
    for (int i = 0; i <(width+height)/times; i++){ 
    grid[i] = 1.0+i;
    }
    print ("grid setup ", grid[10]);
}

void draw (){
  background(0);
  print ("grid draw ", grid[10]);
}
Tagged:

Answers

  • Answer ✓

    Edit post, highlight code, press Ctrl-o to format code.

    You've redefined grid inside setup, hiding the global version that you then use in draw.

  • Thank you for the tip on formatting!

    But here lies my problem, to define the array-size of grid[] i need the Width and Height, that can only be accessed after defining the size() in Setup().

  • @TheSankar -- what koogs is pointing out is a scope problem.

    when you say "float grid[] =" in setup(), you are declaring a new, different grid array inside the scope of setup(). Your global one still exists, and is undefined. draw() can't see the new, private grid that you created in setup. It looks at the global one. Which is a null pointer.

    Instead, since you have already declared grid globally, just initialize that grid inside setup, rather than declaring a new one. We already know it is a float array, so you don't have to say that anymore.

    grid = new float[(width+height)/times];
    
  • Thank you so much Jeremy, I didn't realize the problem! I tried to use "grid[]" without new float before it, but it didn't work... I didn't realized that you needed to take out the []. Thank you so much you guys for the help!

Sign In or Register to comment.