我正在开发一个程序,它从命令行接收一个字符串,分隔出存在非字母字符的单词,然后将它们插入到链表中。例如,hello1world将分为“hello”和“world”。但是,当我注释掉第一个printf语句(如下所示)时,程序不会打印出链表中的第一个单词。当printf语句存在时,代码工作正常。任何帮助将不胜感激。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct _Node {
char * string;
struct _Node * next;
} Node;
Node * head = NULL;
int isSeperator(int ch) {
if(isalpha(ch)) {
return 0;
} else {
return 1;
}
}
void addToList(char * comp) {
Node * temp = NULL;
temp = malloc(sizeof(Node));
temp->string = comp;
temp->next = head;
head = temp;
}
int main(int argc, char * argv[]) {
head = malloc(sizeof(Node));
int i, j, len, lastPos, compLen;
for(i = 1; i < argc; i++) {
lastPos = 0;
char * str;
str = (char*)malloc(sizeof(argv[i]) + 1);
strcpy(str, argv[i]);
strcat(str, "\0");
len = strlen(str);
for(j = 0; j < len; j++) {
compLen = j - lastPos;
char comp[compLen + 1];
if(isSeperator(*(str + j)) == 1) {
memcpy(comp, &str[lastPos], compLen);
strcat(comp, "\0");
addToList(comp);
lastPos = j + 1;
} else {
if(j == len - 1) {
memcpy(comp, &str[lastPos], compLen + 1);
strcat(comp, "\0");
addToList(comp);
}
}
//printf("%s \n", head->string);
}
printf("%s! \n", head->string);
}
return 0;
}