在C結構數組元素必須有一個固定的大小,所以char *theNames[]
無效。你也無法以這種方式初始化結構。在C數組中是靜態的,即不能動態改變它們的大小。
該結構的一個正確的聲明將如下所示
struct potNumber{
int array[20];
char theName[10][20];
};
,你初始化像這樣:
struct potNumber aPot[3]=
{
/* 0 */
{
{10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 /* up to 20 integer values*/ },
{"Half-and-Half", "Almond", "Raspberry", "Vanilla", /* up to 10 strings of max. 20 characters */ }
},
/* 1 */
{
{10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 /* up to 20 integer values*/ },
{"Half-and-Half", "Almond", "Raspberry", "Vanilla", /* up to 10 strings of max. 20 characters */ }
},
/* 2 */
{
{10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 /* up to 20 integer values*/ },
{"Half-and-Half", "Almond", "Raspberry", "Vanilla", /* up to 10 strings of max. 20 characters */ }
}
};
但是,我敢肯定這是不是你想要的。理智的方式來做到這一點需要一些樣板代碼:
struct IntArray
{
size_t elements;
int *data;
};
struct String
{
size_t length;
char *data;
};
struct StringArray
{
size_t elements;
struct String *data;
};
/* functions for convenient allocation, element access and copying of Arrays and Strings */
struct potNumber
{
struct IntArray array;
struct StringArray theNames;
};
個人而言,我強烈建議不要使用裸露的C數組。通過幫助程序結構和功能執行所有操作,可以讓您從緩衝區中清除/超出和其他問題。每個認真的C編碼器都會隨着時間的推移建立一個類似這樣的東西的分支代碼庫。
你會得到什麼錯誤? – 2011-03-02 16:38:59
這真的是你的'struct'是如何定義的? – birryree 2011-03-02 16:46:57