Reputation: 13
I have this issue with assign an int to a char. I have a const char * data, that works like a storage of sizes of differents objects. I use this, to verify if the data have the same size that a object, if is thus, then I append a 2 integer to data. The problem is, that I expected that when I append 2 to data, move 2 positions in ASCII table, but how data behaves as a string, I cannot understand how works this addition.
Example: I have a const char* data that store a char '`', and that have a value of 96, if I make :
data += 2;
I would expect the result to be b, but is < with a value 60.
I use a function sys_log to show what happen.
function Boot:
void Boot(const char* data){
[...]
/*
* OBJECT PROTO
*/
sys_log(0, "BOOT: OBJ PROTO data string: data = %s", data);
sys_log(0, "BOOT: OBJ PROTO size of data: %d", decode_2bytes(data));
if (decode_2bytes(data) != sizeof(TObjectProto))
{
sys_err("object proto table size error");
thecore_shutdown();
return;
}
sys_log(0, "BOOT: OBJ PROTO data after decode_2bytes(data): data = %s", data);
data += 2;
sys_log(0, "BOOT: OBJ PROTO data str + 2: data = %s", data);
size = decode_2bytes(data);
sys_log(0, "BOOT: OBJ PROTO data to size: size = %d", size);
data += 2;
sys_log(0, "BOOT: OBJ PROTO data str + 2: data = %s", data);
sys_log(0, "BOOT: OBJ PROTO data to size: size = %d", decode_2bytes(data));
CManager::instance().LoadObjectProto((TObjectProto *) data, size);
sys_log(0, "To data assign %d * %d", size, sizeof(TObject));
data += size * sizeof(TObjectProto);
sys_log(0, "BOOT: OBJ PROTO data str: data = %s", data);
[...]
decode_2bytes():
inline WORD decode_2bytes(const BYTE *a)
{
return (*((WORD *) a));
}
sys_log :
Apr 12 09:05:54.205886 :: BOOT: OBJ PROTO data string: data = `
Apr 12 09:05:54.205914 :: BOOT: OBJ PROTO size of data: 96
Apr 12 09:05:54.205924 :: BOOT: OBJ PROTO data after decode_2bytes(data): data = `
Apr 12 09:05:54.205933 :: BOOT: OBJ PROTO data str + 2: data = <
Apr 12 09:05:54.205948 :: BOOT: OBJ PROTO data to size: size = 60
Apr 12 09:05:54.205961 :: BOOT: OBJ PROTO data str + 2: data = ½6
Apr 12 09:05:54.205970 :: BOOT: OBJ PROTO data to size: size = 14013
Apr 12 09:05:54.209238 :: To data assign 60 * 40
Apr 12 09:05:54.209247 :: BOOT: OBJ PROTO data str: data = (
As can see in sys_log, I show what contain data, the value, and the result that I obtain when add 2.
Upvotes: 1
Views: 73
Reputation: 27776
data += 2;
I would expect the result to be b, but is < with a value 60.
You just increment the pointer by 2, so it will point to the 3rd character of the string, which is <
. It may even be some random value if the strings happens to end before that.
To increment the value that the pointer points to, you have to dereference the pointer:
*data += 2;
But this will trigger a compiler error, because data
is declared as const char*
.
If you want to modify the string, change the parameter to char* data
.
Upvotes: 2