将函数的返回值设置为数组的大小 [英] Setting a return value from a function as the size of an array
本文介绍了将函数的返回值设置为数组的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个返回整数的函数.我将该值存储在变量"count
"
中
我想定义一个新的char数组,其大小是此返回值.
例如char new_array[count][20]
列宽20是恒定的.这表示最大字符串长度.
但是当我这样做并尝试编译程序时,它给了我错误:
Hi,
I have a function that returns an integer. I store that value in a variable "count
"
I want to define a new char array whose size is this return value.
e.g. char new_array[count][20]
The column width 20 is constant. This represents the max string length.
But when I do this and try to compile the program it gives me the error:
error C2057: expected constant expression
我该怎么做?
How can I do this?
推荐答案
您不能使用变量值声明数组,因为编译器必须在编译时知道数组大小.
您要做的是使用指针创建一个动态数组,如下所示:
Hi,
you can''t declare an array with a variable value, because the compiler has to know the array size at compilation time.
What you have to do is to use a pointer to create a dynamic array like this:
main()
{
int count = 0;
int *DynArray = NULL;
count = GetArraySizeFunction();
DynArray = new int[count];
if( NULL != DynArray)
{
for( int i0 = 0; count > i0; ++i0)
{
DynArray[i0] = 0;
}
// do with the array whatever you want
delete[] DynArray; //Rajesh: Replaced delete with delete[]
//Carlo: Replaced ''Replacedd'' with ''Replaced'' :-\
//Armin: Replaced ''Replacced'' with ''Replacedd'' in Carlos comment ;-)
}
}
如果您使用的是C ++,那么使用std::vector<int>
之类的东西会更好.
向量,列表,队列等都具有良好的性能和可靠性,并且易于使用!
If you''re using C++, then you''d be far better using something likestd::vector<int>
.
Vectors, lists, queues, etc., provide both good performance and reliability, and they''re easy to use!
唯一的方法就是使用指针.
int * myArray = new int [count];
我的语法可能不对,我已经好几年没有使用C ++了,但是核心概念绝对正确-创建动态数组的唯一方法是使用指针.您的另一选择是使用动态容器,例如std :: vector.
The only way to do this is with pointers.
int * myArray = new int[count];
My syntax may be off, I''ve not done C++ for years, but the core concept is definitely right - the only way to create a dynamic array is with pointers. Your other option is to use dynamic containers like std::vector.
这篇关于将函数的返回值设置为数组的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文