我有以下源代码,它为图像,像素和读取像素值分配空间.
#include <stdlib.h>
#include <stdio.h>
typedef struct color
{
int r,g,b;
}color;
typedef struct image
{
int width, height;
color *pixels;
}image;
image* CreateImage(int width, int height)
{
imagem *im=NULL;
im=(image*)malloc(sizeof(image));
im->height=height;
im->width=width;
im->pixels=(color*)malloc(width*height*sizeof(color));
int i;
//error starts here
for (i=0; i<width*height;i++)
{
scanf('%d', &im->pixels[i]->r);
scanf('%d', &im->pixels[i]->g);
scanf('%d', &im->pixels[i]->b);
}
return im;
}
Run Code Online (Sandbox Code Playgroud)
问题始于代码中读取图像像素的部分.当我编译它时,错误是'无效的类型参数' - >'(有'颜色')'
我知道如果左操作数是指针,我们必须使用' - >'.这里的图像和像素是指针,所以为什么我不能使用im-> pixels [i] - > r,例如?我怎么解决这个问题?
pixels确实是一个指针,但你[]对它的使用已经取消引用它.你要:
&im->pixels[i].r
Run Code Online (Sandbox Code Playgroud)
请注意,您的scanf调用应该有一个字符串作为第一个参数,而不是多字符文字 - 在那里使用双引号.