开发者

How can i set same int value to an array of ints

开发者 https://www.devze.com 2023-03-18 21:27 出处:网络
I have a variable: unsigned int* data = (unsigned int*)malloc(height * widt开发者_如何学Goh) I want to set same int to all array values.

I have a variable:

unsigned int* data = (unsigned int*)malloc(height * widt开发者_如何学Goh)

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?


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);


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).


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.


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;


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

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

精彩评论

暂无评论...
验证码 换一张
取 消