0

This program should take 5 NSString's in input and print them. I put them in an NSMutableArray. During the loop if I try to print the NSString's they're printed correctly. But when I try getting the objects from the array, I don't know why it returns null. So if I try printing them in the second loop, they're all null.

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
    NSAutoreleasePool* pool=[[NSAutoreleasePool alloc]init];
    NSMutableArray* array;
    NSString* str=[[NSString alloc]init];
    char* cstr;
    cstr=(char*)calloc(100,sizeof(char));
    for(int i=0;i<5;i++)
    {
        fgets(cstr,100,stdin);
        str=[NSString stringWithUTF8String:cstr];
        [array addObject : str];
    }
    for(int i=0;i<5;i++)
    {
        str=[array objectAtIndex:i];
        NSLog(@"%@",str);
    }        
    [pool drain];
    return 0;
}
2

2 Answers 2

2

In this line:

NSMutableArray* array;

You are declaring array, to be an NSMutableArray, but you're not setting the pointer to anything, so array is just nil.

You want to do this instead to allocate and initialize an actual instance of NSMutableArray and assign it to that pointer:

NSMutableArray* array = [[NSMutableArray alloc] init];
Sign up to request clarification or add additional context in comments.

Comments

2

You haven't initialized your array. You should put: NSMutableArray *array = [[NSMutableArray alloc] init];

or better yet: NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:5];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.