-2

I have a method that concatenates two c string. The method returns a new one. It works fine. Is there a way to make this method void, and just modify the first one?

EDIT: I cannot use strcopy or any other function from the string.h library. It is also suppose to be up to the caller to make sure s1 has enough space to accommodate s2.

char *str_glue(char *s1, char *s2) { char *r; //return string int len1, len2; int i, j; len1 = str_length(s1); len2 = str_length(s2); if ((r=(char*)malloc(len1 + len2 + 1))==NULL) { return NULL; } for (i=0, j=0; i<len1; i++, j++) { r[j] = s1[i]; } for (i=0; i<len2; i++, j++) { r[j] = s2[i]; } r[j] = '\0'; return r; } int main() { char* x = "lightning"; char* y = "bug"; char *z = str_glue(x, y); printf("%s\n", z); } 
2

3 Answers 3

0

Not really. *s1 is a char[] that already has a fixed length. If you write past that length you'll stomp on memory that is not inside of *s1. You have to create a new one that is the length of *s1 + *s2 to avoid this problem like you have done already.

Edit: I guess you could write a function that does what you want if *s1 is big enough to hold itself and *s2. But otherwise, no.

Sign up to request clarification or add additional context in comments.

Comments

0

Use the standard function strcat():

The strcat() and strncat() functions append a copy of the null-terminated string s2 to the end of the null-terminated string s1, then add a terminating `\0'. The string s1 must have sufficient space to hold the result.

Comments

0

You could consider using realloc of s1 provided you allocate the same on the heap. By modifying your code as this, I am able to achieve the same functionality as expected by you.

void str_glue(char **s1, char *s2) { int len1, len2; int i; char *curstr = *s1; len1 = strlen(curstr); len2 = strlen(s2); curstr=(char*)realloc(curstr, (len1 + len2 + 1)); for (i=0; i<len2; i++) { curstr[(len1+i)] = s2[i]; } curstr[(len1+len2)] = '\0'; } 

and main function as

int main() { char* x; char* y = "bug"; x = (char *)malloc(32); strcpy(x, "lightning"); str_glue(&x, y); printf("%s\n", x); } 

You would require to include stdlib.h for realloc definition.

P.S: I am assuming that you don't plan to use the standard C library functions like strcat or others.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.