開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
dev C++
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
string.h
問題(Question):
我用 memcpy (Ptr->ListString, CharPtr, Length);
去餵資料,然後用link list 去存值,在只有兩個字元時,會多了殘餘值。
餵入的資料(Input):
char StringOriginalData[100] = "Abian is son of the bitch";
預期的正確結果(Expected Output):
Abian 5
is 2
son 3
of 2
the 3
bitch 5
請按任意鍵繼續 . . .
錯誤結果(Wrong Output):
Abian 5
iss 2
son 3
ofs 2
the 3
bitch 5
請按任意鍵繼續 . . .
程式碼(Code):(請善用置底文網頁, 記得排版)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char StringOriginalData[100] = "Abian is son of the bitch";
char StringChange[10] = "are";
typedef struct _VOCABULARY_LIST {
char *ListString;
struct _VOCABULARY_LIST *Node;
}VOCABULARY_LIST;
void TearOffAndAdd (VOCABULARY_LIST *Ptr);
int main (int argc, char *argv[]) {
VOCABULARY_LIST *FirstVocabulary;
VOCABULARY_LIST *PtrVocabulary;
FirstVocabulary = (VOCABULARY_LIST *)malloc (sizeof (VOCABULARY_LIST));
PtrVocabulary = FirstVocabulary;
PtrVocabulary->Node = NULL;
TearOffAndAdd (PtrVocabulary);
system("PAUSE");
return 0;
}
void TearOffAndAdd (VOCABULARY_LIST *Ptr) {
char *CharPtr;
VOCABULARY_LIST *NewList;
int Length;
CharPtr = StringOriginalData;
Length = strcspn (CharPtr, " ");
while (Length != 0) {
Ptr->ListString = (char *)malloc (Length * sizeof(char));
memcpy (Ptr->ListString, CharPtr, Length);
printf ("%s", Ptr->ListString);
printf (" %d\n",Length);
NewList = malloc (sizeof (VOCABULARY_LIST));
NewList->Node = NULL;
Ptr->Node = NewList;
Ptr = NewList;
CharPtr += (Length + 1);
Length = strcspn (CharPtr, " ");
}
}
補充說明(Supplement):
這到底怎麼回事?