【发布时间】:2011-12-21 08:05:33
【问题描述】:
【问题讨论】:
-
正如@Mike Seymour 发现的那样,您可能没有正确理解自己的需要。
标签: c++ arrays pointers constants sfml
【问题讨论】:
标签: c++ arrays pointers constants sfml
简单:
// Step 1: Make an array of const values:
const int arr[] = { 1, 4, 9, 17 };
// Step 2: Make a pointer to it:
auto parr = &arr; // 2011-style
const int (*pbrr)[4] = &arr; // old-style
您不能将值“分配”给常量(显然),因此赋予常量一个值的唯一方法是将其初始化为该值。
【讨论】:
*pbrr 周围的括号有什么作用?谢谢!
const int * p = new int[3] { 1, 2, 3 };。
如果您需要动态分配的数组,我建议使用标准容器:
std::vector<Int16> data;
Chunk* c = ...;
data.push_back(...);
c->Samples = &data[0];
【讨论】:
进行分配,将其分配给指向非常量的指针。对数据进行修改。当你做完这些事情后,你可以将你的 const 指针分配给数组。例如:
int * p = new int[100];
for (int i=0; i<100; ++i)
p[i] = i;
const int * cp = p;
【讨论】:
或者,如果在编译时数据未知:
const std::vector<int> function() {
std::vector<int> tmp(5); //make the array
for(int i=0; i<5; ++i)
tmp [i] = i; //fill the array
return tmp;
}
【讨论】:
您不需要const 对象的数组。指向 const 的指针可以指向 const 或非 const 对象;您可以像这样创建一个动态数组并从中初始化一个Chunk 结构:
std::vector<Int16> samples;
initialise(samples);
// valid until 'samples' is destroyed or resized
SoundStream::Chunk chunk = {&samples[0], samples.size()};
【讨论】: