今天,当我在 Objective-C 项目中输入一个方法时,我检查了这一行:
card=self.cards[index];
其中“card”是指向我的类“Card”实例的指针(Card 是 NSObject 的子类)。
在 C 中,如果 card 是一个指针,则这种语法是错误的,因为我必须在“=”和数组名称之间添加“&”字符。
那么,为什么会出现这种差异呢?
“self.cards[index]”是否是返回指针的方法的伪指令?
这就是我想到的解决方案!
谢谢大家!
整个方法是:
-(Card*) drawRandomCard{
Card *card=nil;
if ([self.cards count]) {
unsigned index= arc4random() % [self.cards count];
card=self.cards[index];
[self.cards removeObjectAtIndex:index];
}
return card;
}
最佳答案
In C, if card is a pointer, this syntax is wrong because I have to add the '&' character between '=' and the name of the array.
如果以下情况为真,则不正确:
typedef struct {
...
} Card;
Card *cards[12];
或
Card *cards = malloc(sizeof(Card*) * numCards);
那么这是完全有效的:
Card *card = cards[index];
在 Objective-C 中,self.cards[index]
也是一个指向 Card
类型对象的指针数组。
因此,至少在这方面,它们并没有那么不同。
关于objective-c - C 和 Objective-C 中指针的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35553708/