【发布时间】:2014-06-07 05:11:42
【问题描述】:
您好,我对如何访问结构的成员有一些疑问,以防结构被某些函数通过引用接收。
这是一个生成随机“图像”的程序,并有 2 个我的问题示例:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define WIDTH 16
#define HEIGHT 8
typedef struct
{
int width;
int height;
int maxvalue;
char *pixels;
} image;
void setimagemaxvalue (image *img)
{
scanf ("%d", &((*img).maxvalue); //I know is wrong
}
void createimage (image *img) //just creates a random matrix of pixels
{
(*img).pixels=malloc((img->width)*(img->height));
int i,j;
char *tmp;
tmp=(*img).pixels;
for (i=0;i<(img->height);i++)
{
for (j=0;j<(img->width);j++)
{
*(tmp+(i*(img->width)+j))=(char)(rand()%(img->maxvalue));
}
}
}
int main ()
{
srand(time(NULL));
image img;
img.width=WIDTH;
img.height=HEIGHT;
setimagemaxvalue(&img);
createimage (&img);
return 0;
}
我的问题是:
1) 发送给 scanf 函数的参数应该是什么? (忘记缓冲区清理问题,是的,我知道我可以将结构的 maxvalue 成员发送到“setimagemaxvalue”函数,但这只是一个示例,考虑到它是一个我想知道如何去做结构的成员。
2) 我如何在不使用 tmp 变量的情况下编写函数“createimage”(指针 img 引用指针像素并且它正在引用数据)。
【问题讨论】:
-
为什么你认为它是错误的?
标签: c pointers struct reference