3

见标题。这就是我要问的。对于这个问题,网络没有太多简洁的答案。请记住堆栈与堆。向一个完整的初学者解释。只是寻找“为什么”而不是“如何”。

编辑 指针是一种将大对象从堆栈中取出的方法吗?

4

2 回答 2

3

When passing a huge object from one piece of your program to another to be worked on like an entire class for example or something with a large amount of data like an image or video passing every single bit of data would be very inefficient. Instead you can just pass a tiny little memory address (pointer) that the receiving part of your program can then use to get to the object to be worked on.

Aside from that huge aspect, they offer a lot of flexibility but I need more than a paragraph for that.

When you get into managed code like C# or Java EVERYTHING is done with pointers/references but it's all behind the scenes and you don't have to deal with them like you would in C++ or another similar language. But it's still crucial to understand how they work.

Edit in response to:

"why would I pass a large object around if I don't need to work on it?"

You wouldn't. However; Correct me if I'm straying from what your asking but what you'll learn if you continue into Computer Science is that a piece of your program should be as simple as possible it should only do 1 thing. Commonly known as the Single Responsibility Principle this dictates that you will have many seemingly tiny parts of your program that will all work together to accomplish the over arching goal. That means that a lot of those tiny pieces are going to need to work on the same objects, the same data and use the same tools to get the job done. Lets look at a hypothetical.

You're coding a simple image editing application.You're going to need a cropping tool, a paint brush tool, a selection tool, and a re-size tool. Each of these tools are going to need their own place in your program (a class or more likely many classes that work together) and that class will have many smaller pieces (methods/functions and other things) that work together to accomplish the goal of that class. Every single one of these classes and methods is most likely going to need to look at or modify the image data. With a pointer you can provide them with a memory address instead of making an entire copy of the image. That way when one of the classes or methods makes a change to it you don't need to worry about managing all these copies and making sure they all get the same change.

于 2012-12-20T01:59:28.397 回答
3

它允许您执行按引用传递/共享数据结构,它有两大特点:通过不进行复制来节省内存和 CPU 开销,以及通过更改共享数据来提供复杂的通信模式。

于 2012-12-20T02:06:34.643 回答