Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reverse string

Status
Not open for further replies.

JTan

Technical User
Oct 9, 2001
73
0
0
SG
//I try to duplicate a string. However when I try to print
//it out, there would always be some weird characters
//behind. May I know what is the reason?

/*This is part of the codes from the main function*/

case '5':printf("\tThe duplicate string is: %s.\n",duplicate(text));
break;

/*Duplicate the new string*/
char* duplicate(char *text)
{

return strcat(text,text);

}//duplicate
 
strcat reference in MSDN says:

No overflow checking is performed when strings are copied or appended. The behavior of strcat is undefined if the source and destination strings overlap.
 
In case u are concatnating the two arrays(texts), the length of resultant array should be greater than or equal to the length of the two arrays.

TRY THIS

#include <iostream.h>
#include <string.h>
#include <conio.h>



#define RESET(x) memset(x,0,sizeof(x))

void main(void)
{char first_array[20], second_array_30], result_array[100];

RESET(first_array);
RESET(second_array);
RESET(result_array);

strcat(first_array,&quot;MY FIRST ARRAY - 1 &quot;);
strcat(second_array,&quot;SECOND ARRAY- 2&quot;);

strcat(result_array,first_array);
strcat(result_array,second_array);

clrscr(); gotoxy(20,10);
cprintf(&quot;%s&quot;,result_array);
cin.get(); // press Enter key


}



 
I would use:

/*Duplicate the new string*/
char* duplicate(char *text)
{
char *text2;

text2 = (char *) malloc (strlen (text)+1);
sprintf (text2, text);
return text2;

}//duplicate

As far as I remember strcat doesn't add a zero byte to
terminate the string but sprintf does. When a non-zero byte
terminated string is printed, garbage nearly always results until a zero is found somewhere in memory. However you do it, remember to delete the duplicated string; there isn't any provision in your code (or mine) to do it !
 
oops, that should have been

sprintf (text2, &quot;%s&quot;, text);

 
/*Duplicate the new string*/
char* duplicate(char text[])
{
char text2[50];

strcpy (text2, text);

return strcat(text2,text);

}


char text2[100];

strcpy (text2, duplicate(text));

printf(&quot;\tThe duplicated string is: %s.\n&quot;, text2);



x-)I don't really get what you mean, is that what you want?

Andrew Lim

Trying and exploring is adventuring
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top