简体   繁体   English

声明未知大小的数组

[英]Declaring an array of unknown size

This is not specific to any programming language, the problem is "find the index of a specified value in an array of n numbers. 这并非特定于任何编程语言,问题是“在n个数字的数组中查找指定值的索引。

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 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 可以将数组声明为array = []int[] array = new int[]int array[]array = array() ,´array = {}`等。在某些语言中,您必须声明预先设置数组,并在某些语言中在需要时扩展数组

Of course the first one is correct. 当然第一个是正确的。 In the second one when you declare the array, n is not yet set. 在第二个数组中,当您声明数组时,尚未设置n So it is not correct. 因此,这是不正确的。

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. 但是,假设编程语言或多或少具有静态行为,并且将数组视为内存中静态分配的块(而不是向量等)等,则第一个选项必须正确,因为只有在读取n后才能分配静态数组。

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. 您是否知道编译时或运行时的值取决于您的语言/项目要求,但是在决定创建该大小的数组之前必须先知道该值。 (ie the first solution is correct) (即第一个解决方案是正确的)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM