了解指针? [英] Understanding pointers?

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

问题描述

正如标题所暗示的,我无法确切地理解一个指针是什么,以及为什么他们使用。我搜索了一下周围,但仍然没有真正理解。我在Objective-C的工作为主,但是从我读过这真是多一个C的话题(所以我加了两个标签)。

据我了解,在前面指向内存中的地址的星号的变量?我不明白为什么你会使用一个指向一个值,而不是仅仅使用值本身。

例如:

 的NSString * STRINGVAR = @这是一个考验。

在调用此字符串方法,为什么它的指针,而不只是直接使用字符串?你为什么不使用指针的整数和其他基本数据类型?

有点偏离主题,但我没有正确标签吗?当我写它,我认为这更多的是一个概念设计,而不是一些特定语言,但它特别关注对Objective-C的,所以我客观-C和C标记它。


解决方案

  

我不明白为什么你会使用一个指向一个值,而不是
  只用本身的价值。


当你要引用的值而不是值的副本的特定实例可以使用一个指针。说你要我加倍一定的价值。你有两个选择:


  • 您可以告诉我的什么的值是:5:我请仔细5。这就是所谓的通过的通过值的。我可以告诉你,答案是10,但如果你有5个写下来的地方,仍然5将在那里。谁比谁是指纸张仍然会看到5。


  • 您可以告诉我的其中的值是:请删除我在这里写下的号码,在它的地方写两次这个数​​字这就是所谓的通过的引用的。当我完成后,原来的5不见了,还有它的位置10。谁比谁是指纸将看到10。


指针用于的参考的某一段记忆,而不是的复制的某一段记忆。当你通过引用传递,你传递一个指针,你在谈论的记忆。

As the title suggests, I'm having trouble understanding exactly what a pointer is and why they're used. I've searched around a bit but still don't really understand. I'm working in Objective-C mainly, but from what I've read this is really more of a C topic (so I added both tags).

From what I understand, a variable with an asterisks in front points to an address in memory? I don't quite understand why you'd use a pointer to a value instead of just using the value itself.

For example:

NSString *stringVar = @"This is a test.";

When calling methods on this string, why is it a pointer instead of just using the string directly? Why wouldn't you use pointers to integers and other basic data types?

Somewhat off topic, but did I tag this correctly? As I was writing it I thought that it was more of a programming concept rather than something language specific but it does focus specifically on Objective-C so I tagged it with objective-c and c.

解决方案

I don't quite understand why you'd use a pointer to a value instead of just using the value itself.

You use a pointer when you want to refer to a specific instance of a value instead of a copy of that value. Say you want me to double some value. You've got two options:

  • You can tell me what the value is: "5": "Please double 5 for me." That's called passing by value. I can tell you that the answer is 10, but if you had 5 written down somewhere that 5 will still be there. Anyone else who refers to that paper will still see the 5.

  • You can tell me where the value is: "Please erase the number I've written down here and write twice that number in its place." That's called passing by reference. When I'm done, the original 5 is gone and there's a 10 in its place. Anyone else who refers to that paper will now see 10.

Pointers are used to refer to some piece of memory rather than copying some piece of memory. When you pass by reference, you pass a pointer to the memory that you're talking about.

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

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