为什么在编程中需要指针? [英] Why pointers are necessary in programing?

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

问题描述

在使用任何语言(例如 C 语言)编写代码时使用指针是否重要,是否会占用更多内存.

Is it important to use pointers while writing a code in any language for example C-language does it utilize more memory.

谢谢你

推荐答案

同上 SpyrosP 的评论,即如果不进行长时间的讨论,这个问题很难回答.

Ditto SpyrosP's comment that this question is difficult to answer without going into a long discussion.

我想我的简短回答是:指针对编程是绝对必要的吗?不.它们使一些问题更容易或更清晰地解决,但您总能找到替代解决方案.这就像问:数据库对编程重要吗?"甚至乘法运算符对编程很重要吗?"去掉任何一两个功能,您几乎总能以其他方式使用剩余的功能完成工作.

I guess my short answer would be: Are pointers absolutely necessary to programming? No. They make some problems easier or cleaner to solve, but you could always find alternative solutions. It's like asking, "Are databases important to programming?" or even "Is a multiplication operator important to programming?" Take away any one or two features and you could almost always get the job done some other way with the remaining features.

有很多使用指针的例子.

There are a number of examples where pointers are useful.

例如,当我们想要在两个或多个事物之间创建关联时,指针非常有用,所有这些都可以独立更新.例如,假设我们有一个包含客户信息的内存块,以及另一个包含订单信息的内存块.订单是给一些客户的.我们可以将所有客户信息复制到订单块中.但是如果客户信息发生变化,我们必须在两个地方进行更改.如果我们将多个订单保存在内存中,可能是针对相同或不同客户的,该怎么办?现在,如果客户信息发生更改,我们必须以某种方式知道与该客户相关的订单,并更改所有订单.如果我们在这样做时犯了错误,我们可能会得到相互矛盾的客户信息.

For example, pointers are very useful when we want to create an association between two or more things, all of which might be updated independently. Like, say we have a block of memory with information about a customer, and another block of memory with information about an order. The order is for some customer. We could copy all the customer information into the order block. But then if the customer information changes, we have to change it in two places. What if we are keeping several orders in memory, which might be for the same or different customers? Now if the customer information is changed, we have to somehow know which orders related to that customer, and change all of them. If we make a mistake doing this, we could have contradictory customer information.

但是有了指针,我们可以只有一份客户信息的副本,而订单有一个指向客户的指针.那么如果客户信息发生变化,我们就不需要在每个订单中更新另一个副本,因为每个订单中都没有其他副本".订单都只有一个指向一个副本的指针.我们改变了一个地方,神奇的是所有其他地方都看到了同样的变化.

But with pointers, we could have just one copy of the customer information, and the orders have a pointer to the customer. Then if the customer information changes, we don't need to update another copy in each order because there is no "other copy" in each order. The orders all just have a pointer to the one copy. We change one place, and magically all the other places see that same change.

您可能想要获取有关数据结构的书籍或网站以获取更多示例.

You might want to get a book or find a web site about data structures to get more examples.

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

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