c + +声明基于非恒定变量数组? [英] C++ declare an array based on a non-constant variable?

查看:190
本文介绍了c + +声明基于非恒定变量数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 无效的方法(字符串){
  INT N = a.size();
  int数组[N];
}

以上code能正确编译使用gcc。阵列的大小如何可以来自非恒定变量?该编译器的 int数组自动转化[N] 为int *阵列=新的INT [n]


解决方案

  

如何数组的大小来从非恒定变量?


目前,因为编译器有一个非标准的扩展,它可以让你用C的变长数组在C ++程序。


  

该编译器的 int数组自动转化[N] 为int *阵列=新的INT [n]


这是一个实现细节。我相信GCC它放置在堆栈上,像普通自动变量。它可以或可以不使用如果尺寸为堆栈太大动态分配;我不知道我自己。

void method(string a) {
  int n = a.size();
  int array[n];
}

The above code can compile correctly using gcc. How can the size of the array come from a non-constant variable? Does the compiler automatically translate the int array[n] to int* array = new int[n]?

解决方案

How can the size of the array come from a non-constant variable?

Currently, because that compiler has a non-standard extension which allows you to use C's variable length arrays in C++ programs.

Does the compiler automatically translate the int array[n] to int* array = new int[n]?

That's an implementation detail. I believe GCC places it on the stack, like normal automatic variables. It may or may not use dynamic allocation if the size is too large for the stack; I don't know myself.

这篇关于c + +声明基于非恒定变量数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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