Quote:
|
Originally Posted by myName
I have a a string
char *chMsg = "02222AAA00";
i wana separate this "02222AAA00" into part by part..
Like this "0", "2222", "AAA", "00".
so i declared 4 variables
char *chOne = new char[1]; //"0"
char *chTwo = new char[4]; //"2222"
char *chThree= new char[3]; //"AAA"
char *chFour = new char[2]; //"00"
|
The lengths of each of the new'd arrays are one too short (particularly if you want to treat chOne etc as strings without invoking undefined behaviour).
C-strings include a trailing zero byte, so you need to do this;
char *chOne = new char[2]; //"0"
char *chTwo = new char[5]; //"2222"
char *chThree= new char[4]; //"AAA"
char *chFour = new char[3]; //"00"
Quote:
|
Originally Posted by myName
than,
i use strncpy
strncpy(chOne, chMsg, 1); to get the "0" from "02222AAA00".
|
This is technically OK, unless you attempt to use chOne as a string. For example;
fprintf(stdout, "%s\n", chOne);
will generate undefined behaviour (in practice, a common result will be garbage output, but anything is actually allowed to happen).
To eliminate the undefined behaviour, do this immediately after the above strncpy() call....
Quote:
|
Originally Posted by myName
but how to get the "2222" from "02222AAA00"???
|
I'm assuming you can assume, as in this example, that the "2222" substring starts at the second byte in the string (i.e. at index 1) and you know it is of length 4. In that case, the approach is;
strncpy(chTwo, chMsg + 1, 4);
chTwo[4] = '\0';