[問題] strtok跟遞迴
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
VC++
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
NO
問題(Question):
只要跑到第三層遞迴,就會當掉。
這是NFA to DFA的程式作業。
餵入的資料(Input):
NFAtable 左上(3,0)是NFAtable[1][1]
(3,0)(4,0)(0,0)
(0,0)(3,1)(2,0)
(2,0)(0,0)(4,0)
(3,*)(4,*)(*,*)
預期的正確結果(Expected Output):
DFAtable[state][input] 裡面應該要有 1,3,2
錯誤結果(Wrong Output):
trace temp裡面會變成 錯誤的Ptr
程式碼(Code):(請善用置底文網頁, 記得排版)
int cutString(char *str, int state, int input)
{
char *delim = ",";
char *temp;
temp = strtok(str, delim);
while(temp != NULL)
{
if(strcmp(temp, "0") == 0)
{
return 0;
}
DFAtable[state][input] += ',';
DFAtable[state][input] += temp;
char* pch = new char[3];
strcpy(pch, NFAtable[atoi(temp)][input].c_str());
cutString(pch, state, input);
temp = strtok(NULL, delim);
if(strcmp(temp, "0") == 0)
{
return 0;
}
pch = "";
strcpy(pch, NFAtable[atoi(temp)][input].c_str());
cutString(pch, state, input);
}
}
補充說明(Supplement):
NFAtable跟DFAtable都是string 二維陣列,
遞迴第一次的資料是3,0 1 1 (*str, state, input)
所以第一次temp是3,呼叫cutString資料是2,0 1 1
第二次temp是2,呼叫cutString資料是0,0 1 1
第三次temp是0,所以return 0
這時候會回到第二次,2後面是0,所以再return 0
這時候再回到上一層,3後面是0,但這時候temp裡面會顯示 錯誤Ptr
我有用另一份資料試過,如果只有兩層,就不會有這個問題,
請問是因為我呼叫太多次,導致strtok會有問題嗎?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 1.34.54.4
※ 編輯: kent800909 來自: 1.34.54.4 (04/02 00:47)
→
04/02 00:48, , 1F
04/02 00:48, 1F
推
04/02 00:59, , 2F
04/02 00:59, 2F
→
04/02 00:59, , 3F
04/02 00:59, 3F
→
04/02 00:59, , 4F
04/02 00:59, 4F
→
04/02 01:00, , 5F
04/02 01:00, 5F
→
04/02 01:00, , 6F
04/02 01:00, 6F
→
04/02 01:04, , 7F
04/02 01:04, 7F
→
04/02 01:05, , 8F
04/02 01:05, 8F
→
04/02 01:05, , 9F
04/02 01:05, 9F
推
04/02 01:08, , 10F
04/02 01:08, 10F
推
04/02 01:10, , 11F
04/02 01:10, 11F
推
04/02 11:12, , 12F
04/02 11:12, 12F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章