【发布时间】:2020-09-07 17:28:08
【问题描述】:
我编写了这段代码,其中 readData 接受输入并将值存储在一个结构中,而 writeData 打印这些值。 我需要将 struct Color* 指针值保留在堆内存中,以便我可以从 writeData 函数访问它。出于某种原因,它会在调用 writeData 时保留垃圾值。有人可以帮我弄清楚为什么会这样。谢谢
imageloader.c 文件:
typedef struct Color
{
uint8_t R;
uint8_t G;
uint8_t B;
} Color;
typedef struct Image
{
Color **image;
uint32_t rows;
uint32_t cols;
} Image;
Image *readData(char *filename)
{
FILE *fp = fopen(filename, "r");
char format[3];
int rows = 0, cols = 0, num = 0;
uint8_t R_int = 0;
uint8_t G_int = 0;
uint8_t B_int = 0;
fscanf(fp, "%s\n %d \n %d\n", format, &rows, &cols, &num);
Color** p = (Color** )malloc(rows *cols * sizeof(Color*));
for(int i =0; i< rows *cols; i++)
{
fscanf(fp, "%d %d %d", &R_int, &G_int, &G_int);
Color* c = (Color *) malloc(sizeof(Color));
c->R = R_int;
c->G = G_int;
c->B = B_int;
p[i] = &c;
}
Image *img = (Image*)malloc(sizeof(Image));
img->image = p;
img->rows = rows;
img->cols = cols;
printf("%d", p[0]->R); //garbage value
return img;
}
void writeData(Image *image)
{
}
}
主函数调用readData和writeData
int main(int argc, char **argv)
{
Image *image;
uint32_t rule;
char *filename;
processCLI(argc,argv,&filename);
image = readData(filename);
writeData(image);
freeImage(image);
}
【问题讨论】:
-
p[i] = &c; -
@Zindagi 这个调用有三个转换说明符和四个参数 fscanf(fp, "%s\n %d \n %d\n", format, &rows, &cols, &num);