如何将相同的int值设置为int数组

时间:2011-07-07 15:49:07

标签: c++ memset

我有一个变量:

unsigned int* data = (unsigned int*)malloc(height * width)

我想为所有数组值设置相同的int。 我不能使用memset,因为它适用于字节。

我该怎么做?

5 个答案:

答案 0 :(得分:15)

使用C ++:

std::vector<unsigned int> data(height * width, value);

如果需要将数据传递给需要指针的某些遗留C函数,可以使用&data[0]&data.front()以明确定义的方式获取指向连续数据的指针。 / p>

如果你绝对坚持使用指针(但你没有没有技术原因这样做,我不会在代码审查中接受它!),你可以使用std::fill填补范围:

unsigned int* data = new int[height * width];
std::fill(data, data + height * width, value);

答案 1 :(得分:2)

假设您的阵列内存维度不变:

#include <vector>

unsigned int literal(500);
std::vector<unsigned int> vec(height * width, literal);
vector<unsigned int>::pointer data = &vec[0];

Boost.MultiArray可能会引起您的兴趣,因为您似乎是在这里的空间中索引点(1D数组的维度来自高度和宽度)。

答案 2 :(得分:1)

如果您确信自己想要一个数组,那就用C ++方式做,不要听任何说“malloc”,“for”或“free candy”的人:

#include <algorithm>

const size_t arsize = height * width;
unsigned int * data = new unsigned int[arsize];
std::fill(data, data + arsize, value);

/* dum-dee-dum */

delete[] data; // all good now (hope we didn't throw an exception before here!)

如果您不确定是否需要数组,请使用Konrad says之类的向量。

答案 3 :(得分:0)

我认为你必须使用for循环!

int i;
for (i = 0; i < height * width; i++)
  data[i] = value;

答案 4 :(得分:0)

您已将此标记为C和C ++。它们不是同一种语言。

在C中,您可能需要一个代码片段,如:

// WARNING: UNTESTED
unsigned int* data = malloc(height * width * sizeof (unisgned int));
int i;
for(i = 0; i < height*width; i++)
    data[i] = 1941;
相关问题