gpt4 book ai didi

objective-c - EXC_BAD_ACCESS 错误,Objective-C 问题

转载 作者:行者123 更新时间:2023-12-03 17:30:53 25 4
gpt4 key购买 nike

嘿,我是 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

编辑:我不再收到错误..但现在我有一个新问题。它提示我输入名称,然后立即提示我输入地址,然后我才有机会做任何事情。为什么会发生这种情况?

最佳答案

“inputstring”只是一个 char * - 它未分配,并且没有与之关联的存储。

您必须向其传递一个指向足够大小的数组的指针,使用“a”修饰符并传递一个指向指向scanf的char的指针为您分配。

请参阅 scanf 的手册页 http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/scanf.3.html

关于objective-c - EXC_BAD_ACCESS 错误,Objective-C 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4148999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com