c - How to append a character onto a string? -


the examples i've seen on stack overflow come close problem none of them seem match, have ask myself: how can append character string in c? aware strcat() not job, nor using array values work properly. here 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      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 might guess, purpose of code build string grid of letters particular direction in mind (similar wordsearch). example, if initial string "str" "c" , going in diagonal direction next letter "a", string want put "ca".

when run code, letter not appended. string remains same throughout code, of course causes break. there proper method doing this?

you have bug here:

word[len2 + 1] = grid[posx + nextx][posy + nexty];    //grid[x][y] represents  word[len2 + 2] = '\0'; 

it should be:

word[len2] = grid[posx + nextx][posy + nexty];    //grid[x][y] represents  word[len2 + 1] = '\0'; 

remember index begin 0


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -