Click to See Complete Forum and Search --> : How to put end of string in char array?


dearphael
April 21st, 1999, 10:12 AM
Hi,

I defined an char array of 20 elements
char temp[20];

the problem is, i am copying the contents of another CString to this temp and the CString length is not fixed. during my program, everytime the user selects to rename the temp array, the CString will be copied to the temp array. however, the previous contents of the array are still there.

for example, let's say the first time, CString is myfilename.exe
so temp will be renamed as myfilename.exe

then the second time, if CString is myfile.exe
then temp should also be myfile.exe. but because i do not know how to terminate a char array, the temp is still with the previous length, so now temp becomes myfile.exe.exe

How do i put it such that after copying CString to temp, i can put an end of string in temp so that the previous contents are ignored?

please help

April 21st, 1999, 10:32 AM
You terminate a character string by placing '\0' at the end.

Paul McKenzie
April 21st, 1999, 10:35 AM
There are a few things that I would like to point out concerning your example:

char temp[20];

1) You have space for 19 characters, plus the terminating '\0' character. What if the CString has more than 19 characters? You would get a nasty memory overwrite and may cause an invalid page fault.

2) To adjust the length, you have to write a '\0' to the position in the string that you want to set the length to:
temp[5] = '\0'; // set string length to 5 characters
The terminating 0 determines the length of the string.

3) Why are you mixing character arrays with CStrings? Why not just do this:

CString temp = AnotherCString;

This is safer, and it does not matter what the length is of the string. The CString class allocates the proper amount of memory (in this case, the string is reference counted, so there really isn't any allocation going on), and you don't have to worry about the memory overwrite mentioned in 1).

Regards,

Paul McKenzie

dearphael
April 22nd, 1999, 05:24 AM
Dear Paul,

Thank you

eric33
April 22nd, 1999, 06:57 AM
Just add a null character (0x00) after the last character of the new chain.

Another example is the next :
memcpy( temp, (LPCSTR)string, string.GetLength() +1);
The +1 will copy the ascii null.

April 24th, 1999, 07:02 AM
HI

if YOU hav a variable length string, use the sizeof operator as in C. the size of operator returns the no of bytes for the location so that you can do memory to memory copy of the string from CString to Temp. use the size_t to pass length of the source string in your calling function. if any problem e-mail at anand_iyer77@hotmail.com