objective-c - C 和 Objective-C 中指针的区别

标签 objective-c c arrays pointers

今天,当我在 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/

相关文章:

java - 当我运行代码时,我得到 (0, null) 并且无法弄清楚为什么

c - 如何读入文件,然后将文件中的每个结构放入数组中?

ios - 为什么图像过渡会影响我的动画?

ios - SpriteKit 中的运动轨迹效果?

javascript - 使用 Objective-C 在 iPhone 中创建 MS Word 文档

c - time.h 中是否有设置内部缓冲区的函数

c# - LinQ:C# 在使用一些过滤器复制时对数组进行排序

objective-c - 释放 UIImage imageNamed

c - 测量进程上下文切换

c - 如何在 c 中使用命令行参数(操作系统 : Windows)?