cHam
cHam

Reputation: 2664

manipulating strings in C

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?

Upvotes: 0

Views: 168

Answers (2)

Aamir
Aamir

Reputation: 15556

There is a little change that needs to be done to fix this. Here is the changed code:

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';
int sizeofP = strlen(p);   /////Change Here
    p[strlen(p)] = e[0];//move first char of e to last char of p ***the problem seems to happen here
p[sizeofP + 1] = '\0';  /////Change Here
    strcat(p,"ay");// append "tay" to end
    strcpy(tempP->word,p);
    return tempP;
}

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.

Upvotes: 3

darkpbj
darkpbj

Reputation: 2992

It seems to me that p and e are not getting cleared out all the way, and strcpy is just overwriting as many charcters into p as it needs. The algorithm that it uses in in the man pages, but essentially if the char-array p is not cleared and a shorter string is written in, the null-termination will not exist until after the length of the longest thing written in thus far. (this is why strlen is misleading you as well!)

If you don't fancy clearing p every time (Which you should) you may be able to fool the machine by just appending a,

char newChar = 0

after everytime you assign a value to p

Upvotes: 0

Related Questions