c - 访问通过引用接收的结构体的成员

标签 c pointers struct reference

您好,我对如何访问结构体的成员有一些疑问,以防该结构体由某个函数通过引用接收。

这是一个生成随机“图像”的程序,并有两个我的问题的示例:

#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 引用指针像素并且它引用数据)。

最佳答案

1)关于scanf的参数

scanf ("%d", &((*img).maxvalue));

是读取值的正确方法。 或者您也可以使用

scanf ("%d", &(img->maxvalue));

同样,如果您认为稍后更具可读性,您可以将 (*i​​mg).pixels 替换为 img->pixels

2) 您可以将所有出现的 tmp 替换为 img->pixels

关于c - 访问通过引用接收的结构体的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24093912/

相关文章:

c - 如何运行命令而不等待应用程序退出?

c 编程 : Conversion of < ? :将条件键入简单的 if else

c - 在 C 程序中嵌套 while 循环时遇到问题

c++ - c++ 编译器是否保护 const 内存地址免受任何更改?

c - 为什么 C FAQ 问题 16.7 中的行不一致?

c++ - 使用已删除的 shared_ptr 中的原始指针的未定义行为?

c - 数组到指针的转换是否消除了间接运算符的评估?

json - 在 Go 中解码多个结构中的 json

c - C中结构成员(指针与数组)的内存分配之间的差异

c# - 结构体实现接口(interface)是否安全?