Friday, 15 March 2013

C Segmentation Fault (core dumped) while concatenating strings -



C Segmentation Fault (core dumped) while concatenating strings -

i'm trying write programme in c takes in 3 pointers characters, 2 of strings input user, , lastly string final string user wants write concatenated string to. don't know much memory management, told have utilize malloc * 250 size of each string. told have utilize pointers in order solve problem.

anyways, after inputting both strings via scanf, segmentation fault (core dumped) error no other explanation. i'm guessing has way i'm referencing pointers in str_concat function, don't know start.

here code including str_concat function:

#include <stdio.h> #include <stdlib.h> void str_concat(char* str1, char* str2, char* str); int main() { char* str1; char* str2; char* finalstring; str1 = malloc(sizeof(char)*250); str2 = malloc(sizeof(char)*250); finalstring = malloc(sizeof(char)*250); // input printf("enter string 1: "); scanf("%s", str1); printf("enter string 2: "); scanf("%s", str2); // concatenate str_concat(str1, str2, finalstring); printf("final string: %s\n", finalstring); free(str1); free(str2); free(finalstring); homecoming 0; } void str_concat(char* str1, char* str2, char* str) { // go through string 1 until terminating character while(*str1 != '\0') { *str = *str1; // re-create str1 final string until terminating character str++; // increment position of final string } // end while while(*str2 != '\0') { *str = *str2; // re-create string 2 starting @ final position of string 1 str++; // increment position of final string str2++; // increment string 2 can go through values } // end while *str = '\0'; // add together null terminating character string finish }

your function wrong. forgot increment pointer str1 in loop

while(*str1 != '\0') { *str = *str1; // re-create str1 final string until terminating character str++; // increment position of final string } // end while

the function can written simpler

char * str_concat( const char *str1, const char *str2, char *str ) { char *p = str; while ( *p = *str1++ ) ++p; while ( *p = *str2++ ) ++p; homecoming str; }

take business relationship string functions follow mutual convention according homecoming pointer string.

c string pointers concatenation

No comments:

Post a Comment