Reputation: 315
I have a very basic C question. For context, I am working on a Nordic microcontroller and looking at one of their sample projects. The below function writes the value of value
to the buffer and that data gets sent to the Bluetooth client.
static ssize_t read_long_vnd(struct bt_conn *conn,
const struct bt_gatt_attr *attr, void *buf,
u16_t len, u16_t offset)
{
const char *value = attr->user_data;
return bt_gatt_attr_read(conn, attr, buf, len, offset, value,
sizeof(vnd_long_value));
}
Now when I change one line to a hardcoded value:
const char *value = "A";
It works as expected. The first byte changes to 0x41 which is the ASCII value of 'A'.
Now what if I want to change the first byte to a number for example 32? I tried:
const char *value = 0x20;
but the first byte was not 0x20. I am thinking this change messes with the address location instead of the value or something.
Upvotes: 1
Views: 144
Reputation: 206
The reason const char *value = "A";
works is because "A"
is a string literal. If you used const char *value = 'A';
you would have the same problem as your 0x20
, as this is a character literal.
Another way to write this might be:
const char A[2] = { 'A', '\n' }; // same as "A"
const char *value = A;
So if you just want this pointer to point to a single value you can do the same thing:
const char singleValue[1] = { 0x20 };
const char *value = singleValue;
Upvotes: 0
Reputation: 69306
I am thinking this change messes with the address location instead of the value or something.
You are right. Doing const char *value = NUMBER
you just assign that pointer some arbitrary address, which is not what you want. What you want is to assign that pointer some known address, which points to some arbitrary data.
The simplest way to do this would be to directly allocate that data in the function's own stack, like this:
const char value[] = {32};
Upvotes: 1