gpt4 book ai didi

c - malloc 没有正确分配 3d 数组

转载 作者:太空宇宙 更新时间:2023-11-04 05:37:18 25 4
gpt4 key购买 nike

我正在用 c 编写一个程序,它将读取 ppm 输入文件并将其转换为 ASCII 艺术。在程序中,我分配了一个 3d 数组来存储输入文件的高度和宽度以及 RGB 组件。然后将数组元素(像素)转换为灰度并作为 ASCII 艺术写入输出文件。但是当我尝试编译以下代码时,编译器警告我:

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)); 
^

但是第三个malloc()似乎是对的。为什么?谁能告诉我我做错了什么?

这是我的代码:

#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;
}

最佳答案

你不能写 sizeof(*int) 你必须写 sizeof(int*)

另请参阅 this answer查看如何更好地创建数组

关于c - malloc 没有正确分配 3d 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30400631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com