假设我有这个:
int x;
int x = (State Determined By Program);
const char * pArray[(const int)x]; // ??
在使用 pArray 之前如何初始化它?因为Array的初始大小是由用户输入决定的
Thanks!
如果在运行时确定数组的大小,则无法在编译时初始化数组。
但根据您想要执行的操作,指向 const 数据的非常量指针可能会为您提供所需的信息。
const char * pArray = new const char[determine_size()];
一个更完整的例子:
int determine_size()
{
return 5;
}
const char * const allocate_a( int size )
{
char * data = new char[size];
for( int i=0; i<size; ++i )
data[i] = 'a';
return data;
}
int main()
{
const char * const pArray = allocate_a(determine_size());
//const char * const pArray = new char[determine_size()];
pArray[0] = 'b'; // compile error: read-only variable is not assignable
pArray = 0 ; // compile error: read-only variable is not assignable
delete[] pArray;
return 0;
}
我确实同意其他人的观点,即 std::vector 可能更符合您的需求。如果您希望它的行为更像常量数组,可以将其分配给常量引用。
#include <vector>
int main()
{
std::vector<char> data;
data.resize(5);
const std::vector<char> & pArray = data;
pArray[0] = 'b'; // compile error: read-only variable is not assignable
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)