Errors in Data Structure program using C to concatenate two strings -
#include<stdio.h> #include<conio.h> #include<string.h> void main() { char *s1, *s2, *s3; int length, len1=0,len2=0, i, j; clrscr(); s1=(char*)malloc(20* sizeof(s1)); s2=(char*)malloc(20* sizeof(s2)); printf("enter first string\n"); gets(s1); len1=strlen(s1); printf("enter second string\n"); gets(s2); len2=strlen(s2); length=len1+len2; s3= (char*)malloc((length+2)* sizeof(s3)); for(i=0;i<len1;++i) *(s3+i) =*(s1+i); *(s3+i)=' '; /*leave space @ end of first string */ ++i; for(j=0;j<len2;++j) { *(s3+i)=*(s2+j); /* copying 2nd string */ ++i; } *(s3+i)='\0'; /* store '\0' @ end set 'end of string' */ printf("concatenated string is\n%s", s3); getch(); }
can please point out errors in code, used concatenate 2 strings... showing many errors first asking prototype malloc function..
by looking @ code can using turbo-c compiler. need add #include<alloc.h>
in code.your code correct , worked fine on gcc compiler(after compiler specific adjustment).
but important points learn(sorry if know them):-
1) *(s1+1)=s1[1]
or *(s1+0)=s1[0]
(you can use them interchangeably)
2) if learner fine use gets() starter. beware not safe because in code allocated 20 bytes of memory means can give 20 characters input.but if give input greater 20 characters ??? gets() function store remaining characters beyond allocated 20 bytes. beyond memory used neighboring variables of program.in case neighboring variable s2. hence there chance of changing values of other variables(without knowing).try storing string of length greater 20 in s1 , print both s1 , s2.(you know saying.)(this classic problem).please learn use scanset read strings fast can.
3)after forgot free memory.
4) use new compiler(ex:- gcc),because turbo c made generate code computers of 30 years old now.its better use new compilers,you can find more , support if do.
Comments
Post a Comment