我正在嘗試創建一個名為 history 的 char** ,其中包含如下命令陣列:
做事1
做事2
做事3
做事4
這些命令由用戶一次輸入一個,我希望它們在出現時被添加到這個歷史陣列中。在程式結束時,我想按照撰寫順序將命令列印回用戶。
這是我的代碼:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int BUFFER = 50;
int MAX_ARGS = 100;
int HISTORY_SIZE = 50;
int bufferSize;
//Read in line from user
char* getLine(void){
char* line = NULL;
size_t len = 0;
size_t lineSize = 0;
lineSize = getline(&line, &len, stdin);
return line;
}
int main(){
//declare variables
char *line, *lineCopy;
//history structure
char* history[100];
int historyCount = 0;
do{
//main program loop
//get command
printf("# ");
line = getLine();
//copy command
strcpy(lineCopy, line);
history[historyCount] = lineCopy;
historyCount
}while(historyCount < 4); //while status
for(int i = 0; i < historyCount; i ){
printf("%d: %s\n", i, history[i]);
}
return 0;
}
這樣,陣列中的每個值都被設定為最后輸入的命令,輸出為
做事4
做事4
做事4
做事4
我知道這只是因為我每次都將它指向 lineCopy 的記憶體地址,但我不確定如何修復它并獲取
做事1
做事2
做事3
做事4
uj5u.com熱心網友回復:
字串復制到無效記憶體。
由于每次呼叫 wrapper
getLine()都會為您提供新的記憶體緩沖區,您可以立即使用緩沖區而無需重復。
//copy command
//strcpy(lineCopy, line);
history[historyCount] = line;
historyCount
//or just
history[historyCount ] = getLine();
完成后,您需要釋放所有存盤的行緩沖區
history[]。您沒有檢查包裝器
getline()中的回傳狀態。getLine()
uj5u.com熱心網友回復:
你只需要復制字串
history[historyCount] = strdup(line);
uj5u.com熱心網友回復:
一個問題是您將行復制到 lineCopy,但您從未為 lineCopy 分配記憶體。
并且有一個由 100 個字符指標組成的陣列,每個指標指向 lineCopy 這實際上不是你想要的。因為 lineCopy 將始終指向您案例中最近的字串。這就是為什么您的歷史記錄中的每個命令本質上都是相同的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/433669.html
上一篇:STATA:在逗號后提取子字串
