我想了解你在說什麼「更動態的方法」。 也許你想使列表的數組,其中每個列表(串)可以有不同的尺寸。如果這是你想要的,這個代碼可以幫助:
#include<stdio.h>
#include<string.h>
typedef char * string;
int main()
{
string array1[]={"apple","durian"};
string array2[]={"mustard","carrot","spinach"};
string array3[]={"garlic","onion","pepper", "blackpepper"};
string
* array_of_array[]={ array1,
array2,
array3 };
printf("\n%s %s", array_of_array[0][1],array_of_array[2][3]);
return 0;
}
控制檯結果:
榴蓮blackpepper
但是,如果你的意思是所有的資源必須動態初始化,所以這段代碼可幫助...
#include<stdio.h>
#include<string.h>
typedef char * string;
typedef string * arrayString;
typedef arrayString * arrayList;
string newString(char * temp);
arrayString newArrayString(int size);
arrayList newArrayList(int size);
int main()
{
//Example 1, static allocation, string constant
string array1[]={"apple","durian"};
string array2[]={"mustard","carrot","spinach"};
string array3[]={"garlic","onion","pepper", "blackpepper"};
arrayString Example_One[3]={ array1, array2, array3 };
//Example 2, dynamic allocation using pointer struct
/************************************************************/
arrayList Example_Two=newArrayList(3);
arrayString ExTwoValue1=newArrayString(2);
arrayString ExTwoValue2=newArrayString(3);
arrayString ExTwoValue3=newArrayString(4);
Example_Two[0]=ExTwoValue1;
ExTwoValue1[0]=newString("apple2");
ExTwoValue1[1]=newString("durian2");
Example_Two[1]=ExTwoValue2;
ExTwoValue2[0]=newString("mustard2");
ExTwoValue2[1]=newString("carrot2");
ExTwoValue2[2]=newString("spinach2");
Example_Two[2]=ExTwoValue3;
ExTwoValue3[0]=newString("garlic2");
ExTwoValue3[1]=newString("onion2");
ExTwoValue3[2]=newString("pepper2");
ExTwoValue3[3]=newString("blackpepper2");
/************************************************************/
//Print Result Here...
printf("\n%s %s", Example_One[0][0],Example_One[2][3]);
printf("\n\n%s %s", Example_Two[0][0],Example_Two[2][3]);
return 0;
}
string newString(char * temp)
{
string str = (string)malloc(sizeof(char)*(strlen(temp)+2));
strcpy(str,temp);
return str;
}
arrayString newArrayString(int size)
{
arrayString arrStr= (arrayString)malloc(sizeof(string)*size);
return arrStr;
}
arrayList newArrayList(int size)
{
arrayList arrLst= (arrayList)malloc(sizeof(arrayString)*size);
return arrLst;
}
控制檯結果:
蘋果blackpepper
apple2 blackpepper2
它幾乎* *聽起來像是你試圖製造指針數組的數組常量字符串。我幾乎在那裏使用「因爲」,因爲我讀了你的帖子四次,我仍然無法辨別你所尋找的東西。 – WhozCraig
'char * Example [] [3] = {{「array」,「of」,「strings」},{「array」,「of」,「strings2」},/*...*/};' ? – BLUEPIXY
那麼,我真正想做的是創建一個虛擬內存地址的哈希表。我最初的想法是,使用某種類型的散列,我將特定地址分組爲「桶」。我認爲如果我有一個指向數組的指針數組,我可以實現這一點。儘管我迷失了語法。 –