我有一點麻煩弄清楚爲什麼的strtok()崩潰我的程序的strtok()函數之後崩潰程序調用它被稱爲不止一次
main()
{
NodePtr root, cwd;
char line[128] = {'\0'};
char command[16] = {'\0'};
char pathname[64] = {'\0'};
char dirname[64] = {'\0'};
char basename[64] = {'\0'};
root = (NodePtr)malloc(sizeof(Node));
gets(pathname);
strcpy(root->name, "/");
root->nodeType = 'D';
root->childPtr = NULL;
root->parentPtr = NULL;
root->siblingPtr = NULL;
mkdir(&root, pathname);
mkdir(&root, "/abc/fa");
}
當我打電話的mkdir第一次,一切都按預期工作(更具體地說,使用strtok())。但是一旦mkdir第二次被調用,當mkdir被調用時,我的程序崩潰。
void mkdir(NodePtr *root, char pathname[64])
{
char dirname[64] = {'\0'}; //only local variable for dirname
char basename[64] = {'\0'}; //only local variable for basename
int i = 0;
int j = 0;
int cut = 0;
int numOfDir = 0; //number of directories
int len = 0; //length of entered pathname
char* tok; //temp value to tokenize string and put it into dirPath
char** dirPath; //an array of strings that keeps the pathway needed to take to create the new directory
NodePtr newNode;
NodePtr currNode;
NodePtr currParentNode;
tok = "\0";
........
printf("tok: %s\n", tok);
tok = strtok(pathname, "/"); //start first tokenized part
strcpy(dirPath[i], tok); //put first tokenized string into dirPathp[]
// printf("string: %s\n", dirPath[i]);
i++;
while(i < numOfDir)
{
tok = strtok(NULL, "/");
strcpy(dirPath[i], tok); //put tokenized string into array dirPath[]
// printf("string: %s\n", dirPath[i]);
i++;
}
..........
我的程序在
tok = strtok(pathname, "/");
具體打破第一次調用輸入沒有的strtok保持到的mkdir,這就是爲什麼它的崩潰?對於strtok來說很新穎,所以我很抱歉產生混淆。謝謝!
您是否閱讀過[documentation](http://www.cplusplus.com/reference/cstring/strtok/)?它說*「在第一次調用時,函數需要一個C字符串作爲str的參數,[...]在隨後的調用中,該函數需要一個空指針」* – abelenky