开发者

Declaring an array of unknown size

This is not specific to any pr开发者_如何学Cogramming language, the problem is "find the index of a specified value in an array of n numbers.

Now my question is, in the code below can you declare an array how I have done it.

{int n;
read(n);
int array[n];

......

or is this allowed?

{int n; array[n];
read(n)

I'm thinking the first one is correct.

Thanks in advance.


Converted from a comment as suggested by Merlyn Morgan-Graham

The way an array is declared depends on what language you use. If you are writing pseudo-code you can decide it yourself as long as it communicates the intent and the desired result.

The array can be declared as array = [], int[] array = new int[], int array[], array = array(), ´array = {}` etc. In some languages you have to declare the size of the array beforehand and in some languages the arrays expand when needed


In terms of syntax - that would certainly be programming language dependent. But assuming the programming language behaves more or less statically and treats arrays as statically allocated blocks in memory (rather than vectors, etc.), etc. then the first option must be correct as only after n is read a static array can be allocated.


Of course the first one is correct. In the second one when you declare the array, n is not yet set. So it is not correct.


Normally when creating an array you need to know the size before-hand. Whether you know the value at compile-time or run-time can be dependent on your language/project requirements, but it must be known before you can decide to create an array of that size. (i.e. the first solution is correct)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜