gpt4 book ai didi

c++ - 内存复制导致偏移

转载 作者:行者123 更新时间:2023-11-28 03:15:10 25 4
gpt4 key购买 nike

似乎 memcpy 在我正在复制数据的目标数组中创建了一个偏移量。在这里我生成在 header 中定义的源缓冲区:

float  segments[360*RANGE_INDEX*6];
void GlWidget::GenerateBuffers()
{
// srand( 0 );
int angleIndex = segmentIndex * 20;

for(int i = angleIndex; i < angleIndex + 20; i++)
for(int j = 0; j < RANGE_INDEX; j++)
{
float randNumber = rand() % 255;

for(int k = 0; k < 6; k++)
{
segments[(i*RANGE_INDEX+j)*6+k] = randNumber/255.0f;
}
}
}

我已经使用迭代将源缓冲区初始化为 0。

void GlWidget::exec()
{// memcpy ( void * destination, const void * source, size_t num );

qDebug() << "inside exec()";

int startIndex;
int finalIndex;

startIndex = segmentIndex * 20;
finalIndex = startIndex + 20;
ppi->MemCpyToColorVector(&segments[0*RANGE_INDEX], 0);
}

在这里,我将源复制到目标,我遇到的问题是第一个 i,即角度 0,没关系,每六个顶点的颜色保持不变(0 到 599)。但是,对于角度 1 (i == 1),源缓冲区是正确的,600 到 605 的索引保持相同的值,尽管在目标缓冲区中,颜色、600 和 601 是相同的,而与 603 不同。

    void PlanPositionIndicator::MemCpyToColorVector(float* segments, int angleIndex)
{// memcpy ( void * destination, const void * source, size_t num );

// QVector<float> colors;

size_t bytes;

int index;

index = 0;

bytes = 0;

index = angleIndex * _RANGE_CNT;

index *= 6;

bytes = sizeof(float) * _RANGE_CNT * 6;

memcpy(&colors[index], &segments[index], bytes);
}

这个偏移量是由 memcpy 创建的吗?你怎么看?

最佳答案

memcpy是一个低级函数。它将整个内存从一个指针复制到另一个指针。在复杂的数据结构上使用它,比如 QVector ,在不知道其内部结构的情况下,是解决具体错误的简单方法。如果需要从float *复制数据至 QVector < float >你应该简单地做:

if (colors.size() < (index + _RANGE_CNT * 6))
colors.resize(index + _RANGE_CNT * 6);
for (int i = 0; i < _RANGE_CNT * 6; ++i)
colors[index + i] = segments[index + i];

关于c++ - 内存复制导致偏移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17131202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com