Reputation: 85
I'm really new to Objective C and am trying to write a program to go through the collatz conjecture. When I run the program, it stops after the first scanf and comes up with "EXC_BAD_ACCESS". Here's my code:
int original,i;
NSString *PrintFull;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSLog(@"Collatz Conjecture:");
NSLog(@"Print full results?");
scanf("%s",PrintFull);
NSLog(@"What number should we go up to?");
scanf("%d", &original);
while (original <= 100) {
NSLog(@"\n\n%d", original);
i = original;
while (i != 1) {
if (i % 2) {
i = (i*3)+1;
} else {
i = (i/2);
}
if ([PrintFull isEqualToString:@"yes"]) {
NSLog(@"%d",i);
}
}
original++;
}
}
What am I doing wrong here?
Upvotes: 0
Views: 291
Reputation: 16458
scanf
's arguments after the format string should point to already allocated objects. In this case you've just declared a pointer and passed it in without setting it. scanf
will try to write to this location, but since the pointer contains a garbage value, the application crashes.
scanf
is from the C library 'stdio.h', meaning it doesn't know about NSStrings, which are from the Objective-C 'Foundation' framework.
The following should solve these problems
int original,i;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSLog(@"Collatz Conjecture:");
NSLog(@"Print full results?");
char inputBuffer[80];
scanf("%s", inputBuffer);
NSString *printFull = [NSString stringWithCString:inputBuffer encoding:NSUTF8Encoding];
Upvotes: 2
Reputation: 26329
First, you have to initialize and alloc the NSString
. Second, scanf can't handle NSString
.
Also notice, that class names begin with a capital letter and class instances with a small one.
Upvotes: 1
Reputation: 3634
scanf does not work with with object types such as NSString. Please see SO post - Using scanf with NSStrings.
Upvotes: 2