【发布时间】:2012-10-20 13:17:57
【问题描述】:
我正在尝试编写一个方法来删除字符串的第一个字母并将其附加到字符串的末尾,然后附加“ay”。我使用的是链表结构,它可以工作,但不是 100%,我不知道为什么。它有时会做不应该做的事情,但它似乎会随机添加先前单词的部分内容。例如,输入“到底怎么回事”应该是“hatway hetay ellhay siay rongway”的输出,但它给了我“hatway hetwayay ellhayayay silhayayayay rongway”
这是似乎有错误的部分:
typedef struct wordNodeType
{
char word[MAX_CHARS];
struct wordNodeType *next;// pointer to next node
}WordNode;
struct wordNodeType *tempP;
WordNode* translateWord (WordNode* nextWord)
{
strcpy(e,nextWord->word);
strcpy(p, &e[strlen(e)-(strlen(e)-1)]);// remove first letter
// remove newline char if there
if(p[strlen(p)-1] == '\n')
p[strlen(p)-1] = '\0';
p[strlen(p)] = e[0];//move first char of e to last char of p ***the problem seems to happen here
strcat(p,"ay");// append "tay" to end
strcpy(tempP->word,p);
return tempP;
}
我为节点分配了内存,并且节点在“word”中确实有一个值。我的其余代码工作正常,除了这个让我发疯的小错误!有什么想法吗?
【问题讨论】:
-
另外,我已经验证调用函数每次都会传入一个新节点。
-
e和p声明在哪里? -
我还尝试在每次循环后将值“p”清除为 NULL 或“”,但这也无济于事。
-
为什么它们是全球性的?似乎将单词转换为拉丁语的整个操作都可以在没有全局变量的情况下完成。
-
我不明白你为什么不应该在调试器下启动它,看看每一行的数据会发生什么。无论如何,
p[strlen(p)] = e[0];是不正确的 - 你打破了 '\0' 字符,一切都崩溃了。