[英]c++ : An array of the pointer float type with dynamic size
Is this Correct?这样对吗?
Will stereoBuffer be an array of the pointer float type with size mixQty (ie 2);将stereoBuffer是一个大小为mixQty(即2)的指针浮点型数组吗?
// C++ in Header File
float **stereoBuffer;
// in cpp file inside a function of init
mixQty = 2; // this will be passed in function
stereoBuffer = new float*[mixQty];
for (int i = 0; i < mixQty; ++i) {
stereoBuffer[i] = (float *)malloc(samplerate * 2 * sizeof(float) + 32768);
}
Help and Detail answer will be rewarded.帮助和详细回答将获得奖励。
Is this Correct?
这样对吗?
No .没有。 Mixing
new
and malloc()
is not a good idea.混合使用
new
和malloc()
不是一个好主意。
If you must use dynamic memory allocation, then read this: How do I declare a 2d array in C++ using new?如果您必须使用动态内存分配,请阅读以下内容: How do I declare a 2d array in C++ using new?
Otherwise, use an std::vector
.否则,使用
std::vector
。
Will stereoBuffer be an array of the pointer float type
将stereoBuffer 是一个指针浮点类型的数组
It will be (a pointer to the first element of) an array of type pointer-to-float.它将是(指向第一个元素的指针)浮点指针类型的数组。
Each element of this array will be a pointer to the first element of an array of float.这个数组的每个元素都是一个指向浮点数组第一个元素的指针。
As gsamaras notes, mixing new
and malloc
like this is terrible practice.正如 gsamaras 所指出的,像这样混合
new
和malloc
是一种糟糕的做法。 It's needlessly hard to correctly deallocate and there's no error checking.正确解除分配是不必要的困难,并且没有错误检查。 You could at least use
std::vector<std::unique_ptr<float[]>>
and let it take care of deallocation correctly for you.您至少可以使用
std::vector<std::unique_ptr<float[]>>
并让它为您正确处理释放。
using StereoBuffer = std::vector<std::unique_ptr<float[]>>;
StereoBuffer allocateStereoBuffer(size_t mixQty, size_t samplerate)
{
StereoBuffer buf(mixQty);
for (size_t i = 0; i < mixQty; ++i) {
buf[i] = make_unique<float[]>(samplerate * 2 * 32768); // ?
}
return buf;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.