Hi I just started C and since I started with a scripting language, pointers are hard to grasp.
I'm hoping someone can help me with this baffling problem.
I wrote the code below hoping to make a image manipulating program. I create a white image and output it as ppm type 3 format but I get a strange result.
Code:
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
typedef struct pixel {
float r, g, b;
} pixel;
typedef struct image {
int width, height;
pixel *(data[]);
} image;
void createWhiteImage(image **img, int width, int height) {
int i;
pixel pixels[width*height];
for(i = 0; i < width*height; ++i)
{
pixels[i].r = 255;
pixels[i].g = 255;
pixels[i].b = 255;
}
*img = (image *)malloc(sizeof(image));
(**img).width = width;
(**img).height = height;
(*((**img).data)) = pixels;
}
void imageToP3(char *str, image *img) {
int i;
char tmp[70];
strcpy(str, "P3\n");
sprintf(tmp, "%d %d\n", img->width, img->height);
strcat(str, tmp);
strcat(str, "255\n");
for(i = 0; i < img->width*img->height; ++i)
{
sprintf(tmp, "% 3.0f % 3.0f % 3.0f ", (*(img->data))[i].r, (*(img->data))[i].g, (*(img->data))[i].b);
strcat(str, tmp);
if ( i%10 ==9 ) {
strcat(str, "\n");
}
}
}
pixel getPixel(image *img, int x, int y) {
return (*((*img).data))[img->width * y + x - 1];
}
int main (int argc, char const *argv[])
{
image *b;
char str[10000];
createWhiteImage(&b, 10, 10);
imageToP3(str, b);
printf("%s\n", str);
return 0;
}
Result:
Code:
P3
10 10
255
255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255
255 255 255 255 255 255 255 255 255 255 255 255 255 255 -2 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255
255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 -2 255 255 255 255 255 255 255 255 255
255 255 0 -2 0 0 -2 0 -0 -0 -2 0 -0 255 255 255 255 255 255 255 255 255 -2 255 255 255 255 255 255 0
0 0 0 0 -2 0 0 0 -2 -2 -0 0 0 0 0 -0 0 2422584382005669456248832 -0 255 255 -0 -0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 -2 0 -2 -2 0 -0 -2 0 -0 0 -2 -0 -0 -0 0 0 -0 0 0 0 -2 0
0 0 0 0 0 0 0 0 0 0 -2 -0 nan 0 -2 nan -0 0 0 0 0 -0 255 255 -2 255 0 -0 0 0
0 -0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 255 255 255 255 255 255 255 255 0 0 -2
-2 0 -2 255 0 255 255 255 -2 0 4 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 255 255 255
Why do I get these strange numbers? What am I doing wrong?
Environment: Mac OS X, PPC