Ç - 当使用指针运算,当使用数组索引? [英] C - when to use pointer arithmetic, when to use array indexing?

查看:134
本文介绍了Ç - 当使用指针运算,当使用数组索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C,是当它preferrable使用一个比其他?

In C, when is it preferrable to use one over the other?

推荐答案

通常视情况而定。我不认为有一个经验法则。

It usually depends on the situation. I don't think there's a rule of thumb.

在一些情况下,阵列索引更好。例如,当你分配了一个数组

In some cases, array indexes are better. For example when you have allocated an array

char* ptr = malloc(SIZE);

和你需要 PTR 的值不会改变,因为以后要释放它,那么你可以使用索引工作。

and you need the value of ptr to not change, because you want to free it later, then you can work with indexes.

或者,如果你得到一个指针作为函数参数

Or if you get a pointer as a function argument

void func(char* ptr)

和你需要的阵列上运行,那么你可以增加指针本身,你会不会需要创建一个新的变量作为指标来使用。

and you need to run over the array, then you can increment the pointer itself and you won't need to create a new variable to use as an index.

然而,在大多数情况下,这取决于你自己的preferences。

In most cases however, it depends on your own preferences.

这篇关于Ç - 当使用指针运算,当使用数组索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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