Reputation:
Pointer increment not giving the right value, it points to indeterminate address.
Want to know why *p++= <value>
not pointing to the value I want instead it points to something else
My code:
void run_exe() {
int i;
uint8_t buf[20] = {"0"};
uint8_t *p = NULL;
uint8_t tx_buf[4] = {1,1,1,1};
p = buf;
*p++ = 0x14;
*p++ = 0x20;
*p++ = 0x30;
*p++ = 0x40;
*p++ = 0x50;
*p++ = 0x60;
memcpy( p+6, tx_buf, sizeof(tx_buf));
// ARRAY_SIZE: is the macro just my array length.
for (i = 0; i < ARRAY_SIZE(buf); i++) {
printf("%d ", *(p+i));
}
}
I'm printing the decimal value of HEX but at least I'm expecting the correct value but I get indeterminate value.
I'm expecting the output like this.
14 20 30 40 50 60 1 1 1 1 0 0 0 0 0 0 0 0 0
Output:
0 0 0 0 0 0 1 1 1 1 0 0 0 0 255 127 0 0 0
Upvotes: 0
Views: 253
Reputation: 53006
You need an auxiliary pointer,
uint8_t *ptr;
p = buf;
ptr = p;
*p++ = 0x14;
and so on, because the ++
will modify the pointer's value.
Then,
for (i = 0; i < ARRAY_SIZE(buf); i++) {
printf("%d ", ptr[i]);
}
The ++
post-increment or pre-increment operator, makes the pointer p
point to p + 1
after the expression is evaluated, so your p
is NOT pointing to buf
when you attempt to print it.
EDIT: Of course you can just do this too,
for (i = 0; i < ARRAY_SIZE(buf); i++) {
printf("%d ", buf[i]);
}
but I think the original answer explains the reason which is the important thing.
EXTRA: Also, I am 99.9% sure that this is wrong
uint8_t buf[20] = {"0"};
you meant,
uint8_t buf[20] = {0};
your compiler might be showing you a warning for this initialization which is faulty, because "0"
has pointer type and even though it's convertible to a integer type, it mostly certainly doesn't fit a uint8_t
so you have a overflow issue there.
Upvotes: 4