【问题标题】:C Language: Way to access a field in a structure, within a structure (bit tricky this one)C语言:在结构中访问结构中字段的方法(这个有点棘手)
【发布时间】:2013-11-02 18:28:53
【问题描述】:

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

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 */
    }

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

【问题讨论】:

  • @关于他们的工作方式在这里阅读我的回答stackoverflow.com/questions/19602300/… 可能会有所帮助
  • 感谢您的反馈。我们得到了 & 和 * 运算符的含义,当我们假设使用它们来访问结构字段时,它会变得令人困惑,尤其是那些 '**' 。
  • 陛下,*&amp; 运算符以及括号不能应用于字段名称,例如pbm-&gt;&amp;nrowspbm-&gt;(**pixels)。请将它们排除在外,您的受试者会感谢您的。

标签: c arrays pointers structure


【解决方案1】:

没有取消引用,简单明了

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

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

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

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

【讨论】:

  • 我明白了。 sscanf 呢?我是否正确访问这些字段? sscanf(line,"%d",&pbm->pixels[i][j]->rgb[0])
  • @Digriz 如果你检查operator precedence table,你会发现结构指针解引用(-&gt;)和数组下标([])都比地址运算符(@ 987654331@),这样应该没问题。 pixel 成员索引也很好,因为指针可以作为数组进行索引。
  • 三个short可能大于一个int。 (我从未见过这样的系统,但无论如何你都应该使用正确的类型。)
  • 编译时出现此错误:错误:'->' 的无效类型参数(有 'PIXEL_T')引用此行:sscanf(line,"%d",&pbm->pixels[i ][j]->rgb[0]);这是什么意思?
  • @Digriz 啊是的,因为pixel[i][j]不是指针,所以你必须使用普通结构点访问器.,比如&amp;pbm-&gt;pixels[i][j].rgb[0]
猜你喜欢
  • 1970-01-01
  • 2014-07-06
  • 1970-01-01
  • 2020-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多