Nikhil Kumar
Nikhil Kumar

Reputation: 134

string and character concatenation in C

I was trying to implement LCS in C language, but am stuck at equivalent of following code in C :

return backtrack(C, X, Y, i-1, j-1) + X[i]

I tried using strcat() :

 char *str = sequence(arr,pGene1,pGene2,i-1,j-1);
 char chr= pGene1[i-1];
 char *chr1 = &chr;
 return strcat(str,chr1);

but it gives me a segmentation fault. In the above code sequence is a recursive function.

Upvotes: 0

Views: 132

Answers (2)

Nikhil Kumar
Nikhil Kumar

Reputation: 134

I have used this function and now it works

    char * addchartostring(char * str, char mych){
          int l = strlen(str); 
          char *added = (char*)malloc((l+2)*sizeof(char)); 
          char ch[] = {mych, '\0'}; 
          strcpy(added, str);
          strcat(added, ch);
          return added; 
    }

Upvotes: 0

Paul R
Paul R

Reputation: 213170

You are missing a \0 terminator from chr. Also you don't really need the additional pointer chr1. The following should work:

 char *str = sequence(arr, pGene1, pGene2, i-1, j-1);
 char chr[2] = { pGene1[i-1], '\0' };
 return strcat(str, chr);

Upvotes: 2

Related Questions