如果你不知道他們將會有多大,然後使用動態分配。這裏的主要功能是malloc和free。
下面是關於如何使用您的結構,如果你不知道他們有多大是一個建議:
首先有以下的代碼包括:
#include <stdio.h> /* for printf */
#include <string.h> /* for strcpy, as you cannot directly assign strings to a malloc'd pointer */
#include <stdlib.h> /* for malloc and free, for managing memory dynamically */
然後我們定義鍵和值大小:
const int key_size = 10; /* let's define how big our keys and values will be */
const int value_size = 25;
這裏是你如何使用您的結構:
map.size = 30; /* decide how many keyValues we will have */
map.keyValue = malloc(sizeof(_keyValue) * map.size); /* create storage big enough for 30 _keyValue structs
* malloc will allow you to assign memory to key and treat it as an array
* malloc assigns memory from the heap
* equal to the size specified (30),
* this can be potentially as large as your computer's memory */
map.keyValue[0].key = malloc(sizeof(char) * key_size); /* let's create a key at position 0 */
strcpy(map.keyValue.key, "some key"); /* copying some values into key */
map.keyValue[0].value = malloc(sizeof(char) * value_size); /* let's create some space for a value for the 0th element */
strcpy(map.keyValue.value, "some value");
... /* you process and work with those values as you see fit */
free(map.keyValue[0]) /* malloc assigned memory needs to be returned to the OS as it's manually managed,
* here we free the element at position 0 we created earlier
* if you have more than element here use a loop e.g:
* for (int i = 0; i < map.size; i++) { free(map.KeyValue[i]) }
*/
free(map.keyValue); /* free the keyValue itself that stored all the keyValue structs*/
一個技巧,以下劃線開頭的聲明因爲它們爲語言保留而不鼓勵。
請勿使用以下劃線開頭的名稱;它們基本上被保留以供「實施」使用。 –
另外,更具體的問題; 「嘗試鏈接列表但沒有成功」沒有提供足夠的信息讓某人回答你的問題。 –