How do I avoid segmentation fault when decrementing an array based on key input?

HI,
I have an array of images and I want to step forward and back through them with the up and down keys. I’m getting segmentation fault when I run the following in my testApp:: keyReleased when I hit the bottom of the array with the down key:

  
  
  
  if (key == OF_KEY_UP){  
        imageCount++;  
        if (imageCount == arraySize){  
            imageCount = 0;  
        }  
    }  
    if ((key == OF_KEY_DOWN) && (imageCount == 0)){  
        imageCount == arraySize;  
    }  
    else if (key == OF_KEY_DOWN){  
        imageCount--;  
        if (imageCount < 0){  
            imageCount = arraySize;  
        }  
    }  
  

That was my first attempt. Then I tried:

  
  
  if (key == OF_KEY_UP){  
        imageCount++;  
        if (imageCount == arraySize){  
            imageCount = 0;  
        }  
    }  
    if ((key == OF_KEY_DOWN) && (imageCount == 0)){  
        imageCount == arraySize;  
    }  
    else if (key == OF_KEY_DOWN){  
        imageCount--;  
    }  
  

This doesn’t give me a segmentation fault but also doesn’t give me the loop back around that I want.

How do I deal with decrementing through an array when I get to zero?

Any help is greatly appreciated.

How are you assigning arraySize? Arrays start counting from zero, so the size of the array is out of bounds. The imageCount variable should be from 0 to arraySize-1;

and make sure imageCount is a signed int, not an unsigned int

…but then you would compare an unsigned and a signed int…
why should imageCount be signed? it can’t become negative, minimum is 0… :confused:

hi bilderbuchi,

look at this part of the code:

  
  
        imageCount--;    
        if (imageCount < 0){    
            imageCount = arraySize;    
        }  
  

say imageCount is 0 and an unsigned int, decrementing imageCount will produce the following int: 4294967295, the following if-statement is pointless, as an unsigned int can’t be smaller than 0.

Just try this code-snippet:

  
  
#include <iostream>  
  
int main(int argc, char *argv[]) {  
	unsigned int imageCount(0);  
	std::cout << --imageCount << std::endl;  
}  
  

cheers,

Stephan

yeah i know about uint-wrapping. i got to admit I only considered the code in the second attempt shown, where this problem does not occur as far as I can tell.