[英]Why can't we define the array size by a variable when we write C++ code in vs code?
Why can't we define the array size by a variable when writing C++ in vs code?为什么在vs代码中写C++时不能通过变量来定义数组大小?
l have typed the same code shown below in Dev C++, and such declaration is supported in Dev C++.我在 Dev C++ 中键入了如下所示的相同代码,并且在 Dev C++ 中支持这样的声明。
struct student_
{
char name[11];
char no[11];
int grade;
};
struct student_ stu[n]; // not supported in vs code, but supported in Dev C++
I expect such declaration to be true, but the actual result is error.我希望这样的声明是正确的,但实际结果是错误的。
Variable length arrays are not and have never been a part of standard C++.可变长度数组不是也从未成为标准 C++ 的一部分。 Thus, the size of a statically allocated array must be known at compile time.
因此,静态分配的数组的大小必须在编译时知道。 Some compilers support this functionality as a compiler extension (GCC does for instance), but it is not something portable.
一些编译器支持此功能作为编译器扩展(例如 GCC),但它不是可移植的。 Use
std::vector
as a replacement.使用
std::vector
作为替代。
Arrays in C++ are static, and that's why their size needs to be known druing compile time so appropriate space can be allocated. C++ 中的数组是静态的,这就是为什么在编译时需要知道它们的大小,以便分配适当的空间。 You can initialize the size with a variable, but again that variable must have known constant value at compile time.
您可以使用变量初始化大小,但该变量在编译时必须具有已知的常量值。 For that you can use
constexpr
keyword.为此,您可以使用
constexpr
关键字。
In order for your example to work, n
must be declared like this:为了使您的示例正常工作,必须像这样声明
n
:
constexpr size_t n = 5;
When you directly write a number into the size initializer, that value is naturally known at compile time and thus valid as well.当您直接将数字写入大小初始化程序时,该值在编译时自然是已知的,因此也是有效的。
To solve this issue, you need to select g++ compiler step 1: go to MinGw -> bin -> g++ -> press shift + right mouse button step 2: open visual studio -> go to view -> Command pallete -> search for C++ (UI) -> go to compiler path -> paste the g++ path and then scroll down and select IntelliSense mode select -> g++x64 All done!!要解决这个问题,您需要选择g++编译器步骤1:转到MinGw -> bin -> g++ -> 按shift +鼠标右键步骤2:打开Visual Studio -> 去查看-> 命令面板-> 搜索C++ (UI) -> 转到编译器路径 -> 粘贴 g++ 路径,然后向下滚动并选择 IntelliSense 模式选择 -> g++x64 全部完成! Happy Coding
快乐编码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.