Second Challenge solution -- Array out of bounds issue


Below is my solution to the word list problem.
however, I ran into an issue. I am using the array indexes to check if the same word comes after the word being checked. (At first I used nested for loops but that ran REALLY slow).
Back to my Array out of Bounds issue. If I run this code below, it works and runs very fast but dies as soon as it tries to check past the bounds of the array (y+1).
So, I put in a check
if(y+1 > namescount){
NSLog(@“Hey! %i”,y);

But, I never get into that check. It’s seems like the code is not paying attention to my comparing “y” with ‘namescount’. Very strange. If I put in a number value for ‘namescount’ if(y+1 > 10000), then it works fine. Do I need to in some way turn “y” into an NSUInteger?

The error I am getting makes perfect sense, but I don’t know how to fix it. “
*** Terminating app due to uncaught exception ‘NSRangeException’, reason: ‘*** -[NSCFArray objectAtIndex:]: index (234937) beyond bounds (234937)’”


#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

// Read in file

NSString *nameString = [NSString stringWithContentsOfFile:@"/usr/share/dict/words" encoding:NSUTF8StringEncoding error:NULL];

// Array of strings
NSArray *names = [nameString componentsSeparatedByString:@"\n"];

// Iterate
NSUInteger namescount = [names count];

// NSLog(@“Count: %i”, namescount);

    for (int y=0; y<= namescount; y++){
        //NSLog(@"Inside working on %@, %i", [names objectAtIndex:y],y);
        if(y+1 > namescount){
            NSLog(@"Hey!  %i",y);
        if([[names objectAtIndex:y] caseInsensitiveCompare: [names objectAtIndex:y+1]] == NSOrderedSame){
                NSLog(@" Match %@ %@", [names objectAtIndex:y],[names objectAtIndex:y+1]);
    }// End inside for

[pool drain];
return 0;



The index into an array is one less then the number of objects. An array holding 10 objects is indexed as 0 through 9 so if you try to access object 10 you have stepped past the end of the array.



I got the same problem you did, i.e. the array out-of-bounds issue. Here is how I got out of it. Your “names_count” I called “limit”. I suddenly remembered that all arrays start at index 0 not at 1. Thus your names_count and my limit were both out of bounds by 1. My program worked when I made my for loop for (i = 0, i < limit - 1, i++) Notice the limit - 1. Change your names_count to names_count - 1. You are NOT cutting off the last word in the dictionary array. ex. In an array of 10 items, you are really going from 0 to 9. If you try an index of 10, you are out of bounds. I found the dictionary count was 235887 words. Thus, the words index runs from 0 to 235886. So if you type names_count - 1 in the for-loop you should be fine. Also you might want to do < instead of <=.