I am trying to write a method that removes the first letter of a string and appends it to the end of the string with “ay” appended afterwards. I am using a linked list structure, and it works, but something is not 100% and I can’t figure out why. It does what is’t supposed to sometimes, but it seems to randomly add on parts of previous words. for example, the input “what the hell is wrong” should result as an output of “hatway hetay ellhay siay rongway”, but it gives me “hatway hetwayay ellhayayay silhayayayay rongway”
Here is the piece that seems to have the bug:
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;
}
I have memory allocated for the nodes, and the node does have a value in “word.” The rest of my code works fine except for this minor bug that’s driving me crazy! Any thoughts?
There is a little change that needs to be done to fix this. Here is the changed code:
The problem was that when you wrote First character at the end of
p, you overwrote the'\0'character and hence there was no way to reach the end of the string.