C指针与Objective-C的指针 [英] C pointers vs. Objective-C pointers

查看:184
本文介绍了C指针与Objective-C的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是从一个Objective-C背景的,我试图扩大我在C.一件事知识有我困惑,但是,这在C指针和对象 - 之间的区别。正如你可以在下面的例子中看到,事情似乎表现不同的两种语言之间的一点,我想知道如果你能帮助解释为什么?

I'm coming from an Objective-C background and am trying to expand my knowledge in C. One thing has me confused, however, and that's the difference between pointers in C and Obj-C. As you can see in the examples below, things seem to behave a bit differently between both languages, and I was wondering if you could help explain why?

C code工作罚款:

void myFunction()
{
    int x, *pointerX; 
    pointerX = &x;
    *pointerX = 5;

    // Prints: "x is 5"
    printf("x is: %i", x);
}

的OBJ-C code失败:

- (void)myMethod
{
    NSString *string = @"Caramel coffee", *stringPointer;
    stringPointer = &string;                    // Warning:   Assignemnt from incompatible pointer type
    *stringPointer = @"Chocolate milkshake";    // Exception: Incompatible types in assignment

    NSLog(@"string is: %@", string);
}

问:为什么我不能指定stringPointer字符串的内存地址( stringPointer =放大器;字符串; ),为什么我我能执行 * pointerX = 5; ℃下在,但我不能执行 * stringPointer = @巧克力奶昔; 下的Objective-C?

Question: Why can't I assign stringPointer to the memory address of string (stringPointer = &string;), and why am I able to perform *pointerX = 5; under C, but I can't perform *stringPointer = @"Chocolate milkshake"; under Objective-C?

我认识到,使用对象和C对象 - 交易没有,但我似乎无法找出背后的幕后细节,为什么它不OBJ - C的工作。任何帮助是极大的AP preciated。谢谢! :)

I realize that Obj-C deals with objects and C doesn't, but I can't seem to figure out the behind-the-scenes details as to why it doesn't work in Obj-C. Any help is greatly appreciated. Thanks! :)

推荐答案

在你的第一个例子中, X pointerX 有不同的类型((INT)(INT *)分别)。在第二个例子中,字符串 stringPointer 具备的相同的类型(的NSString * )。尝试,而不是:

In your first example, x and pointerX have different types ((int) and (int *) respectively). In your second example, string and stringPointer have the same type (NSString *). Try instead:

NSString *string = @"Caramel coffee", **stringPointer;

这篇关于C指针与Objective-C的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆