恰好阵列什么[1] [英] What happens to array[1]

查看:101
本文介绍了恰好阵列什么[1]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有code,它的目的是要一个数组,并通过它的工作的一大块。在当前项目中会有这样反而改变变量为char的一个​​因素我宣布它为char数组[1]。这样我就不需要修改我的code和风险增加任何错误,并可以很容易地增加它,如果需求的增长。

I have a large block of code that is designed to take an array and work through it. In the current project there will be only one element so instead of changing the variable to a char i declared it as char array[1]. This way i do not need to modify my code and risk adding any bugs and can easily increase it if the requirements grow.

这似乎编译确定,但我已经成为好奇什么是引擎盖下发生的,我是在浪费内存?这是增加额外的处理时间,将编译器优化了这一切所以这将是没有什么不同,如果我输入它?

It appears to compile ok but i have become curious about what is happening under the hood, am i wasting memory ? is this adding extra processing time, will the compiler optimise it all away so it would be no different if i typed it out ?

任何人都可以解释任何可能的缺点使用数组是这个样子。

can anyone explain any possible drawbacks to using arrays is this way.

我使用C和C ++,这将是他们之间有什么不同?

I use c and c++, would it be any different between them ?

推荐答案

首先,你的code是有效的,但如果你关心的缺点,我可以看到下面列出的问题:

First, your code is valid, but if you care about drawbacks, I can see the issues listed below:

使用数组,你增加与外的界限接入访问它的机会,当你遍历不小心的数组。

Using array, you increase the chance of accessing it with out-of-boundaries access when you loop through the array without being careful.

另一个缺点是,阵列不与多态性相互作用。有时你尝试派生类对象存储到基本类型的数组,对象将被切片,您可能不会注意到。

Another drawback is that array doesn't interact with polymorphism. Sometimes you try to store derived object into an array of base type, object will be sliced and you may not notice.

所以,我不会写数组[1] code。希望这回答大家的一些问题。

So I wouldn't write array[1] code. Hope this answers some of your questions.

这篇关于恰好阵列什么[1]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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