用非常量函数参数初始化数组 [英] Initialize array with a non-const function argument

查看:147
本文介绍了用非常量函数参数初始化数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法用非常量整数初始化数组,或者使现有变量恒定以使其成为有效参数?

Is there any way to initialize an array with a non-const integer, or to make the existing variable constant in order to make it a valid argument?

bool f( const char s[], const int n )
{
    char c[n]; // error: expression must have a constant value
}

推荐答案

否,一般情况下不行.改为使用vector<char> c(n).

No, not in the general case. Use vector<char> c(n) instead.

简化的,几乎正确的解释:如果在编译时不知道n是什么,则编译器也不会.因此,它无法为阵列预留内存.这就是vector存在的原因.

Simplified, almost correct explanation: if you don't know what n is at compile time, neither does the compiler. So it cannot put aside memory for the array. This is why vector exists.

如果您在其他地方需要它,可以始终使用&c[0]来获取指向char的指针.

You can always use &c[0] to get the pointer to char if you need it elsewhere.

但是在C99中是可能的,显然.感谢 @Matt McNabb 指出这一点.如果您可以等待几年,您也许也可以在C ++中对其进行编译.同时,使用vector.

But it is possible in C99, apparently. Thanks to @Matt McNabb for pointing this out. If you can wait a few years you might be able to compile it in C++, too. In the meanwhile, use vector.

如果您坚持在C ++中使用数组",则必须执行以下操作:

If you insist to have an "array" in C++, you would have to do something like:

char* c = new char[n];

如果您的程序不能永远运行或执行得太频繁,您甚至可以直接保留它,而不必费心删除.不过,像Valgrind这样的工具可能会抱怨.

If your program does not run forever, or do this too often, you can even just leave it as it is and not bother deleting. Tools like Valgrind might complain though.

这篇关于用非常量函数参数初始化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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