结构内的 C 语言 : Way to access a field in a structure,(这个有点棘手)

标签 c arrays pointers structure

我们有一个头文件,其中声明了这些结构:

typedef struct{
    unsigned short rgb[3];

}PIXEL_T;

typedef struct{
    int format;
    int nrows;
    int ncolumns;
    int max_color;
    PIXEL_T **pixels;

}PBM_T;

我们正在尝试访问 rgb[0] 字段以向其写入数字。但由于我们是新手,使用“指针的指针”数组被证明是很困难的。这是我们最好的、错误的尝试:

/*pbm was previously declared as a PBM_T structure. rows and columns are auxiliary       variables to send to the nrows and ncolumns field. we're suppose to create a bitmap matrix*/

pbm->(**pixels) = malloc(sizeof(int *)*rows);
if (pbm->(**pixels) == NULL)
ERROR(ERR_ALLOC,"Error allocating memory for the bitmap matrix");

int i;

for(i = 0; i < columns; i++) {
    pbm->pixels[i] = malloc(sizeof(int)*columns);
    }

    pbm->&nrows = rows;
    pbm->&ncolumns = columns;

    while((getline(&line, &len, file_stream)) != 1) {
    getline(&line, &len, file_stream);
    sscanf(line,"%d",&pbm->pixels[i][j]->rgb[0]); /* i and j are for two for cycles we're going to implement */
    }

基本上我们最大的问题是访问该字段的正确方法。所有的 * 和 & 让我们很困惑。如果有人也能简要解释其工作原理,我们将不胜感激。预先感谢您。

最佳答案

没有取消引用,只是简单明了

pbm->pixels = malloc(sizeof(PIXEL_T *)*rows);

if (pbm->pixels == NULL) ...

pbm->pixels[i] = malloc(sizeof(PIXEL_T)*columns);

请注意,我更改了用于分配的类型。您分别分配 int*int。这不起作用,尤其是最后一个,因为三个 short 很可能大于单个 int

关于结构内的 C 语言 : Way to access a field in a structure,(这个有点棘手),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19745330/

相关文章:

c - 减少操作次数

c - 从 appsink 解析数据时出现内部数据流错误

c# - 检查是否已使用数组的所有值

java - 数组索引位置中的元素

javascript - RxJS/Angular 2 - 拆分可观察数组

c - fgets 设置为 char * 导致段错误,动态字符串

c - 函数声明隐藏全局声明

c - Printf 在完成命令之前打印功能中的所有内容?

c - C 中的指针内部结构错误 "' struct.pointer' '.' 意外“

c++ - 数组和指针作为参数和返回值