[英]EXC_BAD_ACCESS error, Objective-C question
嗨,我是Objective-C的新手,而且还是使用Cocoa编程的。.无论如何,我的代码看起来像:
int main(int argc, char *argv[])
{
printf("how many address would you like to input?\n");
int numAddresses;
scanf("%i", &numAddresses);
char *inputString;
NSMutableArray * arrayOfBooks = [NSMutableArray array];
for (int i = 0; i < numAddresses; ++i) {
book * f = [[book alloc] init];
printf("Please input the name of contact %i\n", i+1);
scanf("%s",inputString);
[f setName: inputString];
printf("Please input the address of contact %i\n", i+1);
scanf("%s", inputString);
[f setAddress: inputString];
printf("Please input the birthday of contact %i\n", i+1);
scanf("%s", inputString);
[f setBirthday: inputString];
printf("Please input the phone number of contact %i\n", i+1);
scanf("%s", inputString);
[f setPhoneNumber: inputString];
[f print];
[arrayOfBooks addObject:f];
[f release];
}
for(int i = 0; i < numAddresses; i++){
[arrayOfBooks[i] print];
}
return 0;
}
我基本上只是在制作通讯录。 当我输入名字时,它会引发“ EXC_BAD_ACCESS”错误。 为什么?
#import "book.h"
@implementation book
-(void) setName: (char*) nameInput{
name = nameInput;
}
-(void) setAddress: (char*) addressInput{
address = addressInput;
}
-(void) setPhoneNumber: (char*) phoneNumberInput{
phoneNumber = phoneNumberInput;
}
-(void) setBirthday: (char*) birthdayInput{
birthday = birthdayInput;
}
-(void) print{
printf("Name: %s\n", name);
printf("Address: %s\n", address);
printf("Phone Number: %s\n", phoneNumber);
printf("Birthday: %s\n", birthday);
}
@end
编辑:我不再收到错误..但现在我有一个新问题。 它会提示我输入名称,然后立即提示我输入地址,然后我才有机会做任何事情。 为什么会这样呢?
“输入字符串”只是一个字符*-未分配,并且没有与之关联的存储。
您必须向其传递一个足够大的数组的指针,并使用“ a”修饰符,并传递一个指向 char 指针的指针,以便scanf为您分配。
请参见scanf上的手册页http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/scanf.3.html
一个好主意是使用fgets()
而不是scanf()
。 任何空格(空格,制表符,换行符等)都将导致scanf()
停止解析,基于您试图获取的输入,这可能不是您想要的。
像这样使用fgets()
:
char lineBuffer[100]; // or some number large enough
puts("Enter something:");
if (fgets(lineBuffer, sizeof lineBuffer, stdin))
{
// lineBuffer contains the input, but it also contains the '\n' at the end.
doSomething(lineBuffer);
// etc. etc.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.