Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate two char arrays in c?

Tags:

c

I decided to try to make a concatenating function as strcat doesn't work for chars, only strings.

#include <stdio.h>
#include <string.h>

char concat(char a[], char b[]);

int main ()
{
   char *con =  concat("hel", "lo");
   return(0);
}

char concat(char a[], char b[]){
   int lena = strlen(a);
   int lenb = strlen(b);
   char con[lena+lenb];
   con[0] = a;
   con[lena] = b;
   printf("%s", con);
   return con;
}

This code prints "Ã…ÃÆ". Not sure where I am going wrong?

Thanks

like image 784
Alfie Avatar asked Oct 17 '25 06:10

Alfie


1 Answers

First, you shouldn't return reference to temporary

char con[lena+lenb];

(note that the garbage you get doesn't come from that since you print within the function)

Second, you don't allocate enough memory: should be (with first problem fixed):

char *con = malloc(lena+lenb+1);

then use strcpy/strcat anyway, it's faster, and your original code doesn't do anything useful (mixing chars with array of chars & the size of the arrays isn't known at this moment: that's the reason of the garbage you're getting):

strcpy(con,a);
strcat(con,b);

Or as some suggest that they're unsafe functions, and since we know the size of inputs we can write:

memcpy(con,a,lena);
memcpy(con+lena,b,lenb+1);

Also: the prototype of concat is really wrong. It should be:

 char *concat(const char *a, const char *b){

(as it returns a pointer on chars not a char. And the arguments should be constant pointers so you can use your function with any string)

and you're done (don't forget to free the string when you're done with it)

Fixed code (tested, surprisingly returns hello, maybe because it compiles without errors with gcc -Wall -Wwrite-strings -Werror. My advice: turn the warnings on and read them. You'll solve 80% of your problems that way):

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *concat(const char *a, const char *b);

int main ()
{
    char *con =  concat("hel", "lo");
    printf("%s\n",con);
    return(0);
}

char *concat(const char *a, const char *b){
    int lena = strlen(a);
    int lenb = strlen(b);
    char *con = malloc(lena+lenb+1);
    // copy & concat (including string termination)
    memcpy(con,a,lena);
    memcpy(con+lena,b,lenb+1);        
    return con;
}
like image 59
Jean-François Fabre Avatar answered Oct 19 '25 20:10

Jean-François Fabre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!