0

so I have this task to create mandel fractals in C. I will keep the code simple as it's quite much. The Problem:

  • in the given file, each pixel (char[3]) is calculated separately and then written to stdout via write(1, pixeldata, 3)

  • NOW: as this is not very efficient, I want to first collect all pixels of one line in a char array char line[width*3]

  • everything works, except that the output is very different from the one before (colors look displaced, etc.)

Here's the code:

char pixelData[3];
char line[width*3];
for (y=1; y <= height; ++y) {
...
    for (x=1; x <= width; ++x) {
    ... calculate ...

    // iterate
        for ( .... calculate ...) {
               ... calculate ....
        }
        strncat(line, pixelData, 3);        // after
        // write(1, pixelData, 3);  // before: worked
}
write(1, line, sizeof(line)); // after
memset(line, 0, sizeof(line));

}

It would be pretty cool, if someone could tell me, what I did wrong here... Thanks in advance :)

iwilltry42
  • 45
  • 1
  • 10

1 Answers1

2

You cannot use string functions with char arrays which might contain 0s, nor with char arrays which are not 0-terminated. I believe that pixelData in your code is just an array of three small integers, rather than a printable string. So strncat won't help you. On the other hand, since you always know how long your line is, you don't need strncat to work it out for you.

rici
  • 234,347
  • 28
  • 237
  • 341
  • You're right, pixelData contains of three values for RGB. As I want to first generate a whole line (so append those three values to the existing line) which is (width*3) long before I write it to stdout, how else would I do this? – iwilltry42 May 10 '17 at 19:40
  • @iwilltry: think of it as an array of triplets. The first triplet occupies positions 0-2; the next one 3-5; then 4-6; and so on. (Or you could use two dimensional array.) You might want to look at `memcpy`. – rici May 10 '17 at 19:49
  • Thank you, I worked it out like this: use an int as a running index for the current location in the line[]-array, than memcpy(&line[i*3], pixelData, 3); and increment i. Thank you very much for pointing me in the right direction :) – iwilltry42 May 10 '17 at 20:04