C全局结构错误。赋值困难
我很难为全局结构赋值(像素[3])。我尝试了许多不同的typedef和not组合,但仍然无法理解。我想要三个flag_struct类型的像素结构。此顶部是我的全局部分和功能原型: #包括 #包括C全局结构错误。赋值困难,c,struct,C,Struct,我很难为全局结构赋值(像素[3])。我尝试了许多不同的typedef和not组合,但仍然无法理解。我想要三个flag_struct类型的像素结构。此顶部是我的全局部分和功能原型: #包括 #包括 struct flag_struct { int r; int g; int b; }pixel[3]; bool checkInputs(int argc, int countryCode, int width); int computeHeight(int width,
struct flag_struct
{
int r;
int g;
int b;
}pixel[3];
bool checkInputs(int argc, int countryCode, int width);
int computeHeight(int width, int countryCode);
void printFlag(int width, int height, int countryCode, struct flag_struct pixel[]);
void make_pixel (int r, int g, int b);
void flagColor(int width, int height, int countryCode);
这是我的代码中的函数,它给出了每行像素[]的错误。。。每个错误都声明:error:expected expression before–token
void flagColor(int width, int height, int countryCode)
{
if (countryCode == 1)
pixel[] = 0,85,164, 255,255,255,250,60,50;
else if (countryCode == 2)
pixel[] = 0,0,0, 255,0,0, 255,204,0;
else if (countryCode == 3)
pixel[] = 253,185,19, 0,106,68, 193,39,45;
printFlag(width, height, countryCode, pixel);
return;
}
任何帮助都将不胜感激 可能会有较短的版本,但这应该可以
typedef struct flag_struct
{
int r;
int g;
int b;
} flag_struct;
flag_struct pixel[3];
然后
void flagColor(int width, int height, int countryCode)
{
if (countryCode == 1) {
pixel[0].r = 0;
pixel[0].g = 85;
pixel[0].b = 164;
pixel2[1].r = 255;
//...
pixel[2].b = 50;
}
else if (countryCode == 2) {
// Same as above
}
else if (countryCode == 3) {
// Same as above
}
printFlag(width, height, countryCode, pixel);
return;
}
或者你可以试试
pixel[0] = (flag_struct) { .r = 255, .g = 255, .b = 255 };
pixel[1] = (flag_struct) { .r = 255, .g = 255, .b = 255 };
pixel[2] = (flag_struct) { .r = 255, .g = 255, .b = 255 };
不幸的是,您不能这样设置结构。你可以用这样的东西初始化结构
struct flag_s {
int r,g,b;
} pixel[] = { {.r=1, .g=2, .b=3}, {4, 5, 6} };
但您只能在创建结构时执行此操作
设置结构数组值的一种方法是逐行设置:
pixel[0].r = 1;
pixel[0].g = 2;
pixel[0].b = 3;
pixel[1].r = 4;
pixel[1].g = 5;
然而,我会尝试采取一些不同的方法。考虑将可能需要的标志类型初始化为常量,并将全局标志设置为这些标志。typedef有助于提高清晰度。大概是这样的:
// typedef the struct for clarity
typedef struct flag_s {
int r,g,b;
} flag;
// some possible flags
const flag red_flag = {255, 0, 0 };
const flag green_flag = {0, 255, 0 };
const flag blue_flag = {0, 0, 255};
// our global flag variable
flag f;
// set the flag by country code
void set_flag(int country_code)
{
if (country_code == 1)
// copy from our pre-defined flag constants
f = red_flag;
else if (country_code == 2)
f = green_flag;
else if (country_code == 3)
f = blue_flag;
}
// print the global flag
void print_flag()
{
printf("%d %d %d\n", f.r, f.g, f.b);
}
// try it out!
int main(int narg, char *arg[])
{
set_flag(1);
print_flag();
set_flag(2);
print_flag();
set_flag(3);
print_flag();
return 0;
}