【问题标题】:Assignment of a 2 dimensional struct array二维结构数组的赋值
【发布时间】:2020-12-12 09:24:54
【问题描述】:

我已经定义了一个名为 RGBTRIPLE 的新结构类型,但我无法为其赋值。我正在尝试创建一个测试文件来测试 cs50 中模糊代码的不同部分。

#include <stdio.h>
#include <stdint.h>

typedef uint8_t  BYTE;

typedef struct
{
    BYTE rgbtBlue;
    BYTE rgbtGreen;
    BYTE rgbtRed;
}
RGBTRIPLE;



int main(void)
{
    int height = 3;
    int width = 3;
    RGBTRIPLE image[3][3];
    
    image[2][2].rgbtRed = {{10, 40, 70},{110, 120, 130},{200, 220, 240}};
    image[2][2].rgbtGreen = {{20, 50, 80},{130, 140, 150},{210, 230, 250}};
    image[2][2].rgbtBlue = {{30, 60, 90},{140, 150, 160},{220, 240, 255}};
    
}

我遇到了一个错误

2.c:22:24: error: expected expression
        image[2][2].rgbtRed = {{10, 40, 70},{110, 120, 130},{200, 220, 240}};
                              ^
2.c:23:26: error: expected expression
        image[2][2].rgbtGreen = {{20, 50, 80},{130, 140, 150},{210, 230, 250}};
                                ^
2.c:24:25: error: expected expression
        image[2][2].rgbtBlue = {{30, 60, 90},{140, 150, 160},{220, 240, 255}};

【问题讨论】:

  • image[2][2].rgbtRed 的大小是多少?你在做一个有效的任务吗?
  • 您使用的是初始化,而不是赋值。你必须在这里使用赋值。
  • 对于差异分配与初始化,您可以查看其他 SO post
  • 将大小更改为 3 似乎仍然无法解决问题。

标签: arrays c struct cs50


【解决方案1】:

您应该在声明时初始化这些值。你不能像那样初始化(就像你的代码一样)。那是无效的 C 语法。

#include <stdio.h>
#include <stdint.h>

typedef uint8_t  BYTE;

typedef struct
{
    BYTE rgbtBlue;
    BYTE rgbtGreen;
    BYTE rgbtRed;
}
RGBTRIPLE;

int main(void)
{
    int height = 3;
    int width = 3;
    RGBTRIPLE image[3][3] = {{{10, 40, 70},{110, 120, 130},{200, 220, 240}},{{20, 50, 80},{130, 140, 150},{210, 230, 250}},{{30, 60, 90},{140, 150, 160},{220, 240, 255}}};
    
    printf("%d ",image[2][2].rgbtBlue);
    printf("%d ",image[2][2].rgbtGreen);
    printf("%d ",image[2][2].rgbtRed);

    return 0;
}

输出是:

220 240 255

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-29
    • 2019-07-18
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    相关资源
    最近更新 更多