我已經聲明瞭struct
FOO這樣的:堆對象如何使用堆棧中的數據?
struct foo {
const char* name_lower;
const char* name_caps
//..
};
我在堆上動態創建的foo
實例,並要保存在name_lower
和name_caps
成員變量的值。這是由bar
void bar(foo* entry, const char* str, int delimiter_pos) {
char l[2] = {str[caps_pos-1], '\0'}; // create new string
char c[2] = {str[caps_pos+1], '\0'};
entry->name_lower = &l[0]; // assign these strings the foo instance
entry->name_caps = &c[0];
}
我擔心的函數來完成,因爲我不知道這是否代碼將崩潰做。臨時創建的陣列l
和c
將保存在堆棧中。一旦函數終止,堆棧將被清除,c
和l
可能會消失。
這是否意味着foo
實例將失去它的名稱,即它的引用?如果是這樣,我該如何解決這個問題?
Google針對「動態內存分配」 - http://www.programiz.com/c-programming/c-dynamic-memory-allocation –
我知道關於動態內存分配的原則。這是否意味着我必須通過調用malloc來將l和c存儲在堆上? – null
是的,確切地說。否則它們將指向流從「bar」返回後將包含未定義值的地址。 –