I am writing a program in c that would read the ppm input file and convert it to ASCII art. In the program, I alllocated a 3d array that would store the height and width of the input file and the RGB components. The array elements (pixels) would then be converted to grayscale and written into the output file as ASCII art. But when I tried to compile the following code the compiler warned me about that:
asciiArt.c: In function 'main':
asciiArt.c:48:32 error: expected expression before 'int':
array = malloc(width*sizeof(**int)); ^
asciiArt.c:50:35: error: expected expression before 'int':
array[0] = malloc(height*sizeof(*int)); ^
but the third malloc()
seems to be right. Why? Can anyone tell me what am I doing wrong?
Here is my code:
#include <stdio.h>
#include <stdlib.h>
char method_of_conversion(int greyscale){
if(greyscale >= 230){
return ' ';
}else if(greyscale >= 200 && greyscale < 230){
return '.';
}else if(greyscale >= 180 && greyscale < 200){
return '\'';
}else if(greyscale >= 160 && greyscale < 180){
return ':';
}else if(greyscale >= 130 && greyscale < 160){
return 'o';
}else if(greyscale >= 100 && greyscale < 130){
return '&';
}else if(greyscale >= 70 && greyscale < 100){
return '8';
}else if(greyscale >= 50 && greyscale < 70){
return '#';
}else if(greyscale < 50){
return '@';
}
}
int main(){
char ppmFile[100];
char outputFile[100];
int window_size;
scanf("%s", &ppmFile);
scanf("%s", &outputFile);
// the size of a window of pixels to convert to ascii art character
scanf("%d", &window_size);
FILE *input = fopen(ppmFile, "rb");
FILE *output = fopen(outputFile, "w");
char header[5]; //header = P6
fscanf(input, "%s\n", header);
int width, height, maxPixel; // max pixel is always 255
// read the header from the ppm file
fscanf(input, "%d %d %d\n", &width, &height, &maxPixel);
int ***array;
array = malloc(width*sizeof(**int));
array[0] = malloc(height*sizeof(*int));
array[0][0] = malloc(3*sizeof(int));
int x, y;
for (x = 0; x < width; x++){
for(y=0; y < height; y++){
array[x][y][0] = fgetc(input); //red
array[x][y][1] = fgetc(input); //green
array[x][y][2] = fgetc(input); //blue
int greyscale;
int i, j;
for(i = 0; i < width; i+=window_size){
for(j=0; j < height; j+=window_size){
// greyscale = (red + green +blue)/3;
greyscale = (array[x][y][0] + array[x][y][1] +array[x][y][2])/(3*window_size*window_size);
char c = method_of_conversion(greyscale);
fprintf(output,"%c",c); // write the ASCII art directly in the output file
}
}
}fprintf(output,"\n");
}
free(array);
fclose(input);
fclose(output);
return 0;
}