Concatenating String in C -


this question has answer here:

i have method concatenates 2 c string. method returns new one. works fine. there way make method void, , modify first one?

edit: cannot use strcopy or other function string.h library. suppose caller make sure s1 has enough space 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; }  (i=0, j=0; i<len1; i++, j++) {     r[j] = s1[i]; } (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); } 

not really. *s1 char[] has fixed length. if write past length you'll stomp on memory not inside of *s1. have create new 1 length of *s1 + *s2 avoid problem have done already.

edit: guess write function want if *s1 big enough hold , *s2. otherwise, no.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -