0

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,

Edited by mcodesmart: n/a

3
Contributors
3
Replies
5
Views
6 Years
Discussion Span
Last Post by Bluefox815
0

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. :)

0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.