指针的意义是什么? [英] What is the point of pointers?

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

问题描述

当我可以声明变量时,C ++中的指针的意义是什么?何时使用它们?

解决方案

指针最好由C& C ++在传递给函数的变量之间的差异。



是的,你可以传递一个整个变量或者一个指针(分别是值或引用) / p>

但是如果变量是20兆字节的数组,如果你决定将整个文件读入一个数组呢?传递它的价值将是愚蠢的:为什么你会复制20兆的这个操作,如果你最终修改它(即它是一个超参数)你必须复制这20块megs?



更好的是只是点。你说,这里是一个指向一大块内存的指针。这个小间接节省了大量的时间。



一旦你明白了,一切基本上是一样的。重新排列列表中的项目只是交换指针,而不是复制每个项目,你不需要知道开始时有多大的东西等


What is the point of pointers in C++ when I can just declare variables? When is it appropriate to use them?

解决方案

Pointers are best understood by C & C++'s differences in variable passing to functions.

Yes, you can pass either an entire variable or just a pointer to it (jargon is by value or reference, respectively).

But what if the variable is 20 meg array of bytes, like you decided to read an entire file in to one array? Passing it by value would be foolish: why would you copy 20 megs for this operation, and if you end up modifying it (i.e. it's an out-parameter) you have to copy that 20 megs BACK?

Better is to just "point" to it. You say, "here's a pointer to a big blob of memory". And that little indirection saves a ton of time.

Once you understand that, everything else is basically the same. Rearranging items in a list becomes just swapping pointers rather than copying every item around, you don't need to know how big things are when you start out, etc

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

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