看板 C_and_CPP 關於我們 聯絡資訊
※ 引述《spidermomo (是不是該好樂迪了)》之銘言: : 開發平台(Platform): (Ex: VC++, GCC, Linux, ...) : vc6.0 : 問題(Question): : struct陣列初始化 : 程式碼(Code):(請善用置底文網頁, 記得排版) : struct _Price : { : int p; : char vStore; : BOOL gridPress; : char primeStore; : char markStore[11]; : BOOL prime[10]; : BOOL mark[10]; : }Price[20]; : 請問是否可以一次初始化 _Price裡的p? 這問題竟是最近才想到比較好的作法 Orz.. 若可接受宣告並給宣值時,可考慮這麼做 Price[20]={ { 1},{ 2 },{ 3 },{ 4 },{ 5 },{ 6 },{ 7 },{ 8 },{ 9 },{ 10 }, {11},{12 },{13 },{14 },{15 },{16 },{17 },{18 },{19 },{ 20 }, }; 若是在 C++ 時,確實再用建構子下去做可能好些。 ---- 這方法是最近搞一些特殊 Vector (double**) 時,突然想到的 - stdarg.h void SetP(struct _Price *arr, ...) { unsigned i, cnt; va_list ptr; va_start(ptr, arr); cnt=va_arg(ptr, unsigned); for(i=0; i!=cnt; ++i) arr[i].p=va_arg(ptr, int); va_end(ptr); } 在呼叫端 int main() { int i; SetP(Price, sizeof(Price)/sizeof(*Price), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20); for(i=0; i!=sizeof(Price)/sizeof(*Price); ++i) printf("%d ", Price[i].p); return 0; } 離原 po 設部份初值有點距離 (記憶體時間之動作不同), 但以便利性而言,應已達到其需求。 < 想不到之前被我垢病的 stdarg , 竟還是被抓出來用了.. > 有其它想法之版友,歡迎不吝分享或指正,謝謝各位。 :) -- No matter how gifted you are, alone, can not change the world. -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 180.177.78.41 ※ 編輯: tropical72 來自: 180.177.78.41 (09/29 04:13)
johnhmj:原po用BOOL這表明了有用Windows.h,這可以直接寫成類別了 09/29 04:38
tropical72:win32 api 也可單純以 c language 下去寫,BOOL 也存在. 09/29 04:39
tropical72:(還是我誤會了 windows.h 什麼嗎? XD ) 09/29 04:41
johnhmj:嗯…沒錯都可以,我一直以為Windows.h通常與C++用在視窗上 09/29 04:53
loveme00835:http://codepad.org/DkZ3fn2o 09/29 13:59
tropical72:長見識了,感謝。 09/29 21:20