Shrikant Mahapatra Shrikant Mahapatra - 2 months ago 7
C Question

Passing of character array to a pointer and concatenation of string

I get the concatenation of both the strings when 'c' is printed inside the function.But when the address of the pointer is returned and "i" is printed inside main, the output is not proper.

#include <stdio.h>

char* comp(char* s,char* t)
{
int count=0;
char *c;
c=s;
while(*s!='\0')
s++;
for(;*t!='\0';t++,s++)
*s=*t;
return c;
}

int main(){
char* i;
char c[]= "hello there";
char f[]="world";
i=comp(&c,&f);
printf("%s",i);
return 0;
}

Answer

Problems I see:

Problem 1

You are not null terminating the concatenated string in comp.

char* comp(char* s,char* t)
{
   int count=0;
   char *c;
   c=s;
   while(*s!='\0')
      s++;
   for(;*t!='\0';t++,s++)
      *s=*t;

   // Need this
   *s = '\0';
   return c;
}

Problem 2

You calling the function incorrectly. You need to use:

i=comp(c, f); // Not comp(&c, &f)

Problem 3

The most serious problem is that you are writing over memory that you are not supposed to:

When you use:

char c[]= "hello there";
char f[]="world";

c has enough memory to hold the string "hello there" and f has enough memory to hold the string "world". Trying to write beyond those limits is cause for undefined behavior. You could use:

char c[100]= "hello there";
char f[]="world";
i = comp(c, f);

That will be OK since c has enough space for to hold the concatenated string.