Home > Software design >  I tried creating a function to concatinate str2 to str1 using pointers but it doesn't work as I
I tried creating a function to concatinate str2 to str1 using pointers but it doesn't work as I

Time:12-27

I was making an strcat using pointers in C, however I encountered the following problem in my while loop.

This is my code which fails to add str2 (here t) to str1 (here s):

char *pstrcat(char *s,char *t)
{
    char *start=s;
    while(*s  )
        ;
    while(*s  =*t  ){
        ;
    }
    return start;
}

My main code was:

int main()
{
    char s[35]=" hi nice to meet you ";
    char t[]="ho";
    printf("%s",pstrcat(s,t));
    return 0;
}

Expectations:
I was expecting a output of hi nice to meet you ho but instead got hi nice to meet you.

However when I changed the while loop (first while loop of pstrcat) a little bit it started to work.
The new while loop looked like:

while(*s!='\0')
    s  ;

Problem in brief:
I was unable to understand the difference of the two loops. I think both of them should work since both of them must be ending at '\0' with address of s currently pointing to '\0'.
However I must be wrong if my code isn't working.

CodePudding user response:

There are two problems with the code.

  1. Destination array does not have enough space to accommodate additional chars.
  2. First while loop in pstrcat moves the pointer beyond \0
   while(*s  )
        ;

It can be rewritten as

while(*s)
   s  ;

CodePudding user response:

You probably don't know if one character array is big enough to fit both strings in so it's safer to create a new one but you must remember to free it after you've done with it. To concatenate two null-terminated strings, you could do the following...

char *pstrcat(char *s,char *t)
{
    char *start=malloc(strlen(s)   strlen(t)   1);
    sprintf(start, "%s%s%c", s, t, 0);
    return start;
}

int main()
{
    char s[]=" hi nice to meet you \0";
    char t[]="ho\0";
    char *st = pstrcat(s,t);
    printf("%s",st);
    free(st);
    return 0;
}

CodePudding user response:

Thanks to everyone I managed to solve the problem in the following two ways:

char *pstrcat(char *s,char *t)
{
    char *start=s;
    while(*s  )
        ;/*in the end when *s=='\0' it is checked in while loop and after checking it is incremented to point at void hence we have to decrement once*/
    s--;
    while(*s  =*t  ){
        ;
    }
    return start;
}

char *pstrcat(char *s,char *t)
{
    char *start=malloc(strlen(s) strlen(t) 1);
    sprintf(start,"%s%s%c",s,t,0);
    return start;
}

  • Related