没有新的动态数组(C ++) [英] Dynamic array without new (C++)
问题描述
我是C ++的新手,这是一个非常基本的问题。
I'm new to C++ and this is a very basic question.
在C ++中,只有两种方法来创建动态数组(读一本书,如果我写错了,请更正) 要么是 new
运算符,要么是 malloc()
函数,该函数取自C。
In C++ there are only two ways to create dynamic arrays (read in a book, correct me if I'm wrong) using memory allocation either by new
operator or malloc()
function which is taken from C.
声明数组 int array [size]
时,方括号 []
必须具有 const
。
When declaring an array int array[size]
, the square brackets []
must have a const
.
但是在以下代码中, size
是 unsigned int
变量。
However in the following code size
is an unsigned int
variable.
#include<iostream>
int main() {
using namespace std;
unsigned int size;
cout<<"Enter size of the array : ";
cin>>size;
int array[size]; // Dynamically Allocating Memory
cout<<"\nEnter the elements of the array\n";
// Reading Elements
for (int i = 0; i < size; i++) {
cout<<" :";
cin>>array[i];
}
// Displaying Elements
cout<<"\nThere are total "<<size<<" elements, as listed below.";
for (int j = 0; j < size; j++) {
cout<<endl<<array[j];
}
return 0;
}
虽然编译g ++不会出错,而且程序运行正常。
While compiling g++ throws no error and moreover the program runs perfectly.
问题1:这可能是创建动态数组的另一种方法吗?
Question 1 : Could this be another way to create dynamic array?
问题2:代码正确吗?
问题3 ::如果 []
仅包含 const
,为什么代码起作用?
Question 3 : If []
can only contain const
, why does the code work?
推荐答案
- 正确,您发现了 a
gcc
扩展名。在C中已经允许了很长时间,但是直到C ++ 14才使它成为C ++标准。 - 是的,假设您还不错,代码是正确的使用该语言的非便携式扩展。
- 对于符合标准的编译器,这是正确的。您可以通过提供
-std = c ++ 98
或<来告诉gcc
您不想使用扩展名code> -std = c ++ 11 编译器标志。
- Correct, you have discovered a
gcc
extension. This has been allowed in C for a long time, but it has not made it into C++ standard until the C++14. - Yes, the code is correct, assuming that you are fine with using non-portable extensions to the language.
- This is true about standard-compliant compilers. You can tell
gcc
that you do not want to use extensions by supplying a-std=c++98
or-std=c++11
compiler flag.
如果需要动态C ++中的数组大小,更好的方法是使用 std :: vector< T>
。它为您提供了动态分配数组的灵活性,并为您管理分配的内存。
If you need a dynamically-sized array in C++, a better approach would be to use std::vector<T>
. It gives you the flexibility of dynamically allocated array, and takes care of managing the allocated memory for you.
这篇关于没有新的动态数组(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!