2013-11-26 29 views
0

我很難將值分配給我的全局結構(像素[3])。我已經嘗試了很多與typedef不同的組合,但仍然無法弄清楚。我想要三個類型爲flag_struct的像素結構。這個頂部是我的全局部分和函數原型: 的#include 的#includeC全局結構錯誤。難以分配值

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); 

這是我的代碼是給我的錯誤像素...每個錯誤狀態的[]每行的功能:錯誤:表達式之前的期望表達式。

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; 
} 

任何幫助都將不勝感激!

回答

0

可能有更短的版本,但這應該工作。

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 }; 
0

不幸的是,你不能設置結構的方式。你可以用這樣的東西來初始化結構,但是你只能在創建結構時才能做到這一點。設置你的結構的數組的值

的一種方法是行由行:

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; 
}