-
please check
Code:
#include<stdio.h>
#include<stdlib.h>
void con(char*,char*);
int len(char*);
char s[]="xxxxx";
char s2[]="yyyy";
main()
{
char *s1=&s2;
char *s0=&s;
con(s0,s1);
printf("%s",s);
}
void con(char *a,char *d)
{
int sl=len(a);
int sd=len(d);
printf("%d\n%d",sl,sd);
int ex=sl+sd;
char *su=(char *)realloc(a,10);
su=a+sd;
while(*d!='\0')
{
*su++=*d++;
}
printf("%s",s);
*su='\0';
}
int len(char *s1)
{
char *q=s1;
while(*q!='\0')
q++;
return q-s1;
}
OMG... this is string concat program please check this error and tell me....
Thank you
-
-
Look at this for how your problem might be able to resolved.
Code:
char *s1 = "one", *s2 = "two";
char *concat = (char*)malloc( strlen(s1) + strlen(s2) + 1 );
strcpy( concat, s1 );
strcpy( concat + strlen(s1), s2 );
printf( "%s\n%s\n%s\n", s1, s2, concat );
free( concat );
I don't think realloc is appropriate in your code.
-
Code:
strcpy( concat + strlen(s1), s2 );
@ twomaers: I can't able to understand.... could you explain the process....
-
That line of code is equivalent to:
Code:
strcpy( &concat[strlen(s1)], s2 );
Does it make sense now? It copies the string s2 to the concat buffer at the strlen(s1)th position of that buffer, which achieves the concatination you are wanting.
-
@ twomaers : But I want to do it in no extra space. which means use only those str1 and str2 variables only....
-
Well, you need to allocate a buffer big enough for this to work. The following code doesn't work. Try it:
Code:
char *test = "testing";
char *test2 = (char*)realloc( test, 30 ); // You should get an error here
The test variable is effectively a char[8] in this case, which won't allow reallocation.
So, to get what you want you probably want something:
Code:
char *test = (char*)malloc( 5 );
char *test2;
strcpy( test, "test" );
printf( "%s (%d)\n", test, strlen(test) );
// The would result in an error if uncommented: strcat( test, "test" );
test2 = (char*)realloc( test, 20 );
strcat( test2, "test" );
printf( "%s (%d)\n", test, strlen(test) );
you have sufficient memory for your allocation.