0

I have a variable:

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

I want to set same int to all array values. I can't use memset because it works with bytes.

How can i do that?

4

5 回答 5

15

Using C++:

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

If you need to pass the data to some legacy C function that expects a pointer, you can use &data[0] or &data.front() to get a pointer to the contiguous data in a well-defined manner.

If you absolutely insist on using pointers throughout (but you have no technical reason to do this, and I wouldn’t accept it in code review!), you can use std::fill to fill the range:

unsigned int* data = new int[height * width];
std::fill(data, data + height * width, value);
于 2011-07-07T15:50:24.793 回答
2

Assuming your array memory dimension is invariant:

#include <vector>

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

Boost.MultiArray might be of interest, since you appear to be indexing points in a space here (dimension of your 1D array comes from height and width).

于 2011-07-07T15:54:18.053 回答
1

If you are confident that you want an array, do it the C++ way, and don't listen to anyone who says "malloc", "for" or "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!)

If you don't know for sure that you need an array, use a vector like Konrad says.

于 2011-07-07T15:55:36.313 回答
0

I think you'll have to use a for loop!

int i;
for (i = 0; i < height * width; i++)
  data[i] = value;
于 2011-07-07T15:51:00.707 回答
0

You have tagged this a both C and C++. They are not the same language.

In C, you probably want a code fragment like:

// WARNING: UNTESTED
unsigned int* data = malloc(height * width * sizeof (unisgned int));
int i;
for(i = 0; i < height*width; i++)
    data[i] = 1941;
于 2011-07-07T16:03:07.047 回答