Hello,

Please see the code below. it combines 2 strings into one.

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

int main() 
{ 
       char a[10], b[10], *p = NULL, *combine(char *s, char *t);

	   strcpy(a, "horse");
	   strcpy(b, "fly");

	   p = combine(a,b);
	   printf("%s\n",a);
	   printf("%s\n",b);
	   printf("%s",p);
	  
} 

char *combine(char *s, char *t)
{
	int x,y;
	char r[50];

	strcpy(r,s);
	y = strlen(r);
	for (x = y; *t != '\0'; ++x)
		r[x] = *t++;

		r[x] = '\0';
		return r;
}

Why can't I print the combined "p" in this code. This is similar to strcat.

Thanks,

Recommended Answers

All 3 Replies

Local variables are destroyed when the parent function returns. In combine(), the r array is a local variable. Even if you return a pointer to it, the array will still cease to exist when combine returns.

Two ways around that problem are passing a buffer and returning a pointer to dynamic memory.

char *combine(char r[], char *s, char *t)
{
	int x,y;

	strcpy(r,s);
	y = strlen(r);
	for (x = y; *t != '\0'; ++x)
		r[x] = *t++;

		r[x] = '\0';
		return r;
}
char *combine(char *s, char *t)
{
	int x,y;
	char *r = malloc(50);

	strcpy(r,s);
	y = strlen(r);
	for (x = y; *t != '\0'; ++x)
		r[x] = *t++;

		r[x] = '\0';
		return r;
}

Edward's changes are not perfect. Buffer parameters also need a size to avoid buffer overflow, and dynamic memory needs to be handled safely by checking for failure. But those make the code more complex, and Ed trusts you to fill in the blanks. :)

Thanks, this works..
i overlooked such an obvious fact

On a personal note, I'd recommend the buffer method for good practice because the dynamic memory method makes it very easy for a memory leak to occur.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.