0

Iterating through 1D array (pseudo 2D) with step of 3:

arr = new int[height * width * 3];
for (int i = 0; i < height * width * 3; i+=3) {
  arr[i] = 1;   
}

I have tried this, but what I got is column of one third:

for (int y = 0; y < height * 3; y++) {
    for (int x = 0; x < width; x+=3) {
        arr[x + width * y] = 1;
    }
}
0

2 Answers 2

3

Assuming your cells have a 'size' of 3 entries, you should use the * 3 on the inner loop. Otherwise you miss 2 thirds of your cells on each row. You also need to multiply width by 3 to get the correct row.

for (int y = 0; y < height; y++) {
    for (int x = 0; x < width * 3; x+=3) {
        arr[x + width * 3 * y] = 1;
    }
}

In general you need the following structure for such situations:

for (int y = 0; y < height; y++) {
    for (int x = 0; x < width * cellWidth; x+= cellWidth) {
        arr[x + width * cellWidth * y] = 1;
    }
}

(Were cellWidth is 3 in your case)

To slightly simplify this, you could assume in the loops that your cells have a width of 1 (like a normal situation) and multiply by cellWidth when actually assigning the values:

for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
        int index = (x + width * y) * cellWidth;
        arr[index + 0] = 1; // First 'cell entry'
        arr[index + 1] = 1; // Second
        ...
        arr[index + cellWidth - 1] = 1; // Last
    }
}

Another solution is to create larger 'items' using a struct for example:

typedef struct { int r, int g, int b } t_rgb;
t_rgb* arr = new t_rgb[height * width];
for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
        arr[x + width * y].r = 1;
    }
}

and you are able to use it as a regular array (the compiler does all calculations for you). This also makes it more clear what is happening in your code.

Sign up to request clarification or add additional context in comments.

Comments

1

What are you trying to accomplish exactly? Setting a channel in a RGB image? I usually do it like this:

for (int y = 0; y < height; y++)
    for (int x = 0; x < width; x++)
        arr[(x + width * y) * 3] = 1;

In general, to set RGB values, you can simply add an offset like this:

for (int y = 0; y < height; y++)
    for (int x = 0; x < width; x++)
    {
        size_t base = (x + width * y) * 3;
        arr[base + 0] = r;
        arr[base + 1] = g;
        arr[base + 2] = b;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.