How to copy character array to another character array in 'c' using pointers and without using string library

How can I copy a character array to another character array in C

using pointers and without using a string library?

I've tried this:

Header file:

char strconcat(char a[100], char b[100]) {
    int i=0,j=0;
    while(a[i] != '\0'){
        i++;
    }
    while(b[j] != '\0'){
        a[i] = b[j];
        j++;
        i++;
    }
    return a[100];
}

      

+3


source to share


3 answers


 char *strconcat(char *dst, const char *src)
 {
     char *bak = dst;
     while (*dst) dst++;
     while (*dst = *src)
     {
          dst++;
          src++;
     }
     return bak;
 }

      

Note that there can be no char a[100]

. In C, this notation is automatically converted to char a[]

, which is equivalent char *a

.



You also don't need to compare things with 0. Omitting the comparison will happen by default.

+3


source


void strconcat(char *a, char *b)
{

 int i=0,j=0;
 while(a[i++]!='\0')
         ;
 while(b[j]!='\0')
       a[i++]=b[j++];
 a[i] = '\0';
}

      



0


source


The first version naively assumes enough space at the destination,

char *
my_strcat(char *destp, char *srcp)
{
    if(!destp) return(destp); //check that dest is valid
    if(!srcp) return(destp);  //check that src is valid
    char *dp=destp; //save original destp
    while(*dp) { dp++; }      //find end of destp
    while(*srcp)
    {
        *dp++ = *srcp++;      //copy src to dest, then increment
    }
    return(destp);
}

      

The second version allows you to specify the maximum size for the destination,

char *
my_strncat(char *destp, char *srcp, long max)
{
    if(!destp) return(destp); //check that dest is valid
    if(!srcp) return(destp);  //check that src is valid
    char *dp=destp; //save original destp
    long x=0;
    while(*dp && (x<max)) { dp++; ++x; }      //find end of destp
    while(*srcp && (x<max))   //copy from src while more space in dst
    {
        *dp++ = *srcp++; ++x; //copy src to dest, then increment
    }
    *dp = '\0'; //ensure destination null terminated
    return(destp);
}

      

0


source







All Articles