我正在為 Elon Musk 建造火箭,記憶體使用對我來說非常重要。
我有文本和指向它的指標pText。它在堆中令人不寒而栗。
有時我需要分析字串,它的單詞。我不在堆中存盤子字串,而是存盤兩個指標開始/結束以表示文本的子字串。但有時我需要列印這些子字串以進行除錯。我怎么做?
我知道要列印字串我需要兩件事
- 指向乞討的指標
- 末尾的空終止符
有任何想法嗎?
// Text
char *pText = "We've sold the Earch!";
// Substring `sold`
char *pStart = &(pText 6) // s
char *pEnd = &(pStart 3) // d
// Print that substring
printf("sold: %s", ???);
uj5u.com熱心網友回復:
如果您只想列印子字串,請為 使用精度引數printf:
printf("sold: %.*s", (int) (pEnd - pStart) 1, pStart);
如果您需要以其他方式使用子字串,那么最簡單的方法可能是創建一個臨時字串,復制到其中,然后列印出來。
也許是這樣的:
// Get the length of the sub-string
size_t length = pEnd - pStart 1;
// Create an array for the sub-string, 1 for the null-terminator
char temp[length 1];
// Copy the sub-string
memcpy(temp, pStart, length);
// Terminate it
temp[length] = '\0';
如果您需要多次執行此操作,我建議您為此創建一個通用函式。
您可能還需要malloc根據用例動態分配字串。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/338873.html
