Friday 15 March 2013

Concatenating two strings in C -



Concatenating two strings in C -

so have create function concatenate 2 strings in c; function creates new string concatenating str1 , str2. function has phone call malloc() or calloc() allocate memory new string.the function returns new string.

after executing next phone call printf() in main test function: printf ( “%s\n”, mystrcat( “hello”, “world!” )); printout on screen has helloworld!

here's code far; can't quite understand why not work. doesn't anything... compiles , runs nil displayed.

#include <stdio.h> #include <stdlib.h> #include <string.h> char *my_strcat( const char * const str1, const char * const str2); int main() { printf("%s", my_strcat("hello", "world")); // test function. output of print statement supposed helloworld } char *my_strcat( const char * const str1, const char * const str2) { char *temp1 = str1; // initializing pointer first string char *temp2 = str2; // initializing pointer sec string // dynamically allocating memory concatenated string = length of string 1 + length of string 2 + 1 null indicator thing. char *final_string = (char*)malloc (strlen(str1) + strlen(str2) + 1); while (*temp1 != '\0') //while loop loop through first string. goes long temp1 not nail end of string { *final_string = *temp1; // sets each successive element of final string equal each successive element of temp1 temp1++; // increments address of temp1 can feed new element @ new address final_string++; // increments address of final string can take new element @ new address } while (*temp2 != '\0') // same above, except string 2. { *final_string = *temp2; temp2++; final_string++; } *final_string = '\0'; // adds null terminator thing signify string homecoming final_string; //returns final string. }

you're returning final_string, it's been incremented during course of study of algorithm point null terminator - not origin of string.

you need alter allocation like:

char *final_string_return = malloc(strlen(str1) + strlen(str2) + 1); char *final_string = final_string_return;

and later on:

return final_string_return;

c string

No comments:

Post a Comment