Fill array with other array question

Jan 14, 2015 at 4:58pm
Hello all,

I ave a more or an efficiency question, I have an array of pixels now the array is built up like this

unsigned char* blue = new unsigned char[W*H*3];

each pixel consists out of 3 chars B,G,R so pixel one is

1
2
3
blue[i] = 255;
blue[i + 1] = 0;
blue[i + 2] = 0;


now I can loop though the whole array and clear the array one pixel at a time to the color i want, but what i really want to do is just set the whole array to a color.

I could do something like this
 
memset(blue, 255, W*H*3);

but then i set all the color values to 255 and then i get white.

so my question is is there a fast way to fill an array with lets say a smaller array?
Jan 16, 2015 at 11:52am
1
2
3
4
5
6
7
8
9
10
#define W 10
#define H 10
#include <cstring>
int main()
{
    unsigned char img[3][W][H];
    ::memset(img[0], 255, W*H); //What you want
    ::memset(img[1], 124, W*H); //Additional
    return ((img[0][0][0] == 255) && (img[1][0][0] == 124)); //True
}


With dynamic array:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <vector>
//read: http://www.cplusplus.com/forum/beginner/53965/

int main()
{
    std::size_t height (0), width(0);
    std::cout << "Input height: "; std::cin >> height;
    std::cout << "Input width: "; std::cin >> width;

    //C++ wont let us use new[3][width][height]

    std::vector<std::vector<std::vector<unsigned char> > > img;
    img.resize(3);
    for(auto& i : img)
    {
        i.resize(width);
        for(auto& u : i) u.resize(height);
    }

    //what you want
    img[0] = std::vector<std::vector<unsigned char>>(width,std::vector<unsigned char>(height,255));
    return img[0][0][0] == 255;
}


So, basically, you have to change the only-pointer variable to a 3D array with the first "size" == 3.
Last edited on Jan 16, 2015 at 12:57pm
Jan 16, 2015 at 12:24pm
unsigned char *** img = new unsigned char[3][width][height]; Illegal C++. All array dimensions aside from first should be compile time constants.
Even if it was legal, return type will be unsigned char (*)[width][height] and not triple pointer.
Jan 16, 2015 at 12:58pm
@MiiNiPaa I was fixing my reply ;).
Jan 16, 2015 at 1:17pm
Again, lines 13-19 can be replaced by
std::vector<std::vector<std::vector<unsigned char> > > img{3, {3, {3}}};

Also OP want fast method (he uses 1D representation of 3D array, and it seems like it is a screen buffer which is probably has some requirements on memory layout).

OP, It seems like your first approach would be best and it is probably will be neatly optimised. You can try to create a struct for pixel, check if no padding bytes were added and either create an array of structs or cast your buffer pointer to struct pointer and use it. It might make your code clearer, but I doubt that will make significant improvements.
Topic archived. No new replies allowed.