remington howell
remington howell

Reputation: 170

How to append a character onto a string?

The examples I've seen on Stack Overflow come close to what my problem is but none of them seem to match, so I have to ask myself: How can I properly append a character to a string in C? I am aware that strcat() does not do the job, nor does using array values work properly. Here is my code:

char* buildWord(int posX, int posY, int nextX, int nextY, int gridX, int gridY, char** grid, char* str, int length){
    int len2;
    char* word = malloc(sizeof(char) * 20);

    if(posX+nextX < 0 || posX+nextX > gridX)
        return NULL;
    if(posY+nextY < 0 || posY+nextY > gridX)
        return NULL;

    strcpy(word, str);
    len2 = strlen(word);
    word[len2 + 1] = grid[posX + nextX][posY + nextY];    //grid[x][y] represents a 
    word[len2 + 2] = '\0';                                //single character
    printf("%s", word);

    length++;

    if(length < 4)
        word = buildWord(posX+nextX, posY+nextY, nextX, nextY, gridX, gridY, grid, word, length);

    return word;
}

As you might guess, the purpose of this code is to build a string from a grid of letters with a particular direction in mind (similar to a wordsearch). For example, if my initial string "str" is "c" and am going in a diagonal direction where the next letter is "a", the string I want to put together is "ca".

When I run this code, the letter is not appended. The string remains the same throughout the code, which of course causes it to break. Is there a proper method to doing this?

Upvotes: 1

Views: 92

Answers (1)

You have a bug here:

word[len2 + 1] = grid[posX + nextX][posY + nextY];    //grid[x][y] represents a 
word[len2 + 2] = '\0';

It should be:

word[len2] = grid[posX + nextX][posY + nextY];    //grid[x][y] represents a 
word[len2 + 1] = '\0';

Remember that the index begin with 0

Upvotes: 3

Related Questions