Search code examples
cstructconcatenationc-stringsfunction-definition

String concatenation without libraries in C


I am having trouble concatenating strings in C without library function. I tried the following:

#include <stdio.h>

struct word {
  char *str;
  int wordSize;
};

void concat(struct word words[], int arraySize, int maxSize) { // word array, its size, and max size given
  char result[maxSize];
  int resultSize = 0;
  struct word tmp;

  for (int i = 0; i < arraySize; i++) {
    tmp = words[i];
    for (int j = 0; j < words[i].wordSize; j++,  resultSize++) {
      result[resultSize + j] = tmp.str[j];
    }
  }

  puts(result);
}

For example, if the struct array words contain [{"he", 2}, {"ll", 2}, {"o", 1}], the result should be hello. However, this code prints h�l�o where the second and fourth letters are questionmark. Can anyone help me debug this?


Solution

  • Keep it simple and the bugs will fix themselves. Don't mix up the position in the result buffer with the loop iterators. No need for temporary variables.

    #include <stdio.h>
    
    typedef struct {
      char *str;
      int wordSize;
    } word;
    
    void concat(word words[], int arraySize, int maxSize) { 
      char result[maxSize];
      int count=0;
      
      for(int i=0; i<arraySize; i++)
      {
        for(int j=0; j<words[i].wordSize; j++)
        {
          result[count]= words[i].str[j];
          count++;
        }
      }
      result[count] = '\0';
      
      puts(result);
    }
    
    int main()
    {
      word w[3] = { {"he", 2}, {"ll", 2}, {"o", 1} };
      concat(w, 3, 128);
    }