我正在研究一個程序,它應該搜索註冊表中的特定值,並將它們和它們的路徑存儲在一個數組中。所以我不知道程序會找到多少個鍵,因此我需要使用動態增長的數組。我現在使用此代碼,但我不確定它是否正確。什麼是爲結構動態分配內存的正確方法?
struct data
{
char * Path;
char * Key;
};
struct data **RegArray = NULL;
int ArrayCount = 0;
// ....
// ....
// search the registry here....
// value has been found, so i should add it to the array here
RegArray = (struct data **)realloc(RegArray, (ArrayCount + 1) * sizeof(struct data *));
RegArray[ ArrayCount ] = (struct data *)malloc(sizeof(struct data));
RegArray[ ArrayCount ]->Path = _strdup(CurrentPath);
RegArray[ ArrayCount ]->Key = _strdup(CurrentKey);
ArrayCount++;
有人可以告訴我,如果這可能是好的,或沒有。如果不是,我該如何正確做?
謝謝!
realloc不能用於未分配的數據 –
@AlterMann:'NULL'指針上的'realloc'相當於'malloc'。 – netcoder
netcoder,你是對的,對不起 –