2016-07-10 49 views
6

所以我想在一个函数中创建一个数组,其大小由作为参数的数字设置。这里是一个例子:在没有全局变量的情况下在C++中创建一个数组

void temp_arr (const int array_size) { 
    int temp_arr[array_size]; //ERROR array_size needs to be a constant value 
    //Then do something with the temp arr 
} 

即使参数是一个const int,它也不会工作。我想不使用全局常量,也不使用向量。我只是好奇,因为我正在学习C++。我希望它能够使每次调用函数时数组的大小都不相同。有没有解决这个问题,或者我是否要创建一个const变量和函数调用之前的数组?

+0

'INT * temp_arr =新INT [ARRAY_SIZE] ... delete [] temp_arr;' – songyuanyao

+0

@songyuanyao这不是真的,因为它会从静态分配到动态分配。 – user2296177

+1

*并且不使用矢量。我只是好奇,因为我正在学习C++。* - 所以你认为'std :: vector'不是C++?为什么很多初学者认为他们不应该使用或不能使用它,这与'vector'有什么关系? – PaulMcKenzie

回答

7

使用模板功能:

template<std::size_t array_size> 
void temp_arr() 
{ 
    int temp_arr[ array_size ]; 
    // ...work with temp_arr... 
} 

然后,您可以调用函数的语法如下:

temp_arr<32>(); // function will work with a 32 int statically allocated array 

注意

array_size不同的值每次调用将实例一个新的功能。

+2

如果大小来自变量会怎么样? – Dmitri

+0

@Dmitri仅当它是'constexpr'时:'constexpr std :: size_t sz {32}; temp_arr ();'会工作。重点是,它必须在编译时可用。 – user2296177

+0

这对我有用。我正在使用一个const int传入模板。 – kingcobra1986

2

当您在此函数中传递值时,该值不是常量。定义一个数组必须用一个常量值来完成。尽管您已经使用了const int array_size,但它只会创建一个在该函数内保持不变的整数。所以在某种程度上,如果你在函数中传递一个变量值,它将它作为一个变量。因此它会产生一个错误。是的,您需要创建一个常量并在函数调用期间传递它。

+0

我厌倦了在main中有一个const int并将其传递给函数。我也试着在函数中添加一个等于array_size的const int。你是说我应该创建一个全局变量? – kingcobra1986

+0

@ kingcobra1986你不必创建一个全局变量,查看我的答案。 – user2296177

+0

@ kingcobra1986如user2296177的回答所示,不需要创建全局变量。 –

0

可以使用:

int const size = 10; 
int array[size]; 

在C创建阵列++。但是,您不能使用

void temp_arr (const int array_size) { 
    int temp_arr[array_size]; 
} 

创建一个数组,除非编译器支持将VLA作为扩展。该标准不支持VLA。

参数类型中的const限定符仅在函数中使变量const - 您无法修改其值。但是,该值不一定在编译时确定。

例如,使用可以调用函数:

int size; 
std::cout << "Enter the size of the array: "; 
std::cin >> size; 
temp_arr(size); 

由于值不能必然地在编译时决定的,它不能被用来创建一个数组。

+2

参数类型中的'const'限定符不是“无用的” –

0

如果没有与内存问题让我来告诉你一个简单的方法: -

void temp_arr (const int array_size) 
    { 
     //lets just say you want to get the values from user and range will also be decided by the user by the variable array_size 

     int arr[100]; //lets just make an array of size 100 you can increase if according to your need; 
     for(int i=0; i<array_size ; i++) 
     { 
     scanf("%d",&arr[i]); 
     } 
    } 

我知道这是不适合初学者一个完美的解决方案,而只是一个简单的方法。

+1

您应该包含一些代码以防止缓冲区溢出,当它们的大小超过100时 –

+0

完全同意@ M.M它只是将想法提供给初学者。 – dreamBegin

+0

我也在学习编程的道路上,我只想分享我所知道的东西。 – dreamBegin

0

你可以使用一个std ::的unique_ptr:

void temp_arr(int array_size) 
{ 
    auto temp_arr = std::make_unique<int[]>(array_size); 
    // code using temp_arr like a C-array 
} 
相关问题