I would like to initialize a 16-byte array of hexadecimal values, particularly the 0x20 (space character) value.
What is the correct way?
unsigned char a[16] = {0x20};
or
unsigned char a[16] = {"0x20"};
Thanks
I would like to initialize a 16-byte array of hexadecimal values, particularly the 0x20 (space character) value.
What is the correct way?
unsigned char a[16] = {0x20};
or
unsigned char a[16] = {"0x20"};
Thanks
There is a GNU extension called designated initializers.
This is enabled by default with gcc
With this you can initialize your array in the form
unsigned char a[16] = {[0 ... 15] = 0x20};
Defining this, for example
unsigned char a[16] = {0x20, 0x41, 0x42, };
will initialise the first three elements as shown, and the remaining elements to 0
.
Your second way
unsigned char a[16] = {"0x20"};
won't do what you want: it just defines a nul-terminated string with the four characters 0x20
, the compiler won't treat it as a hexadecimal value.
int
you'll get 32
and if you print as char
you'll get ` ` (space). –
Hymenium There is a GNU extension called designated initializers.
This is enabled by default with gcc
With this you can initialize your array in the form
unsigned char a[16] = {[0 ... 15] = 0x20};
unsigned char a[16] = {0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20};
or
unsigned char a[16] = "\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20";
I don't know if this is what you were looking for, but if the size of the given array is going to be changed (frequently or not), for easier maintenance you may consider the following method based on memset()
#include <string.h>
#define NUM_OF_CHARS 16
int main()
{
unsigned char a[NUM_OF_CHARS];
// initialization of the array a with 0x20 for any value of NUM_OF_CHARS
memset(a, 0x20, sizeof(a));
....
}
The first way is correct, but you need to repeat the 0x20,
sixteen times. You can also do this:
unsigned char a[16] = " ";
"<16 spaces>"
will actually occupy 17 bytes (the last one for '\0'). –
Walrus I would use memset
.
No need to type out anything and the size of the array is only provided once at initialisation.
#include <string.h>
int main(void)
{
unsigned char b[16];
memset(b, 0x20, sizeof(b));
}
© 2022 - 2024 — McMap. All rights reserved.
0x2
is not the space character, but an integer. – Tansey0x20
– Susceptible0
; I meant0x20
, of course). If you mean space, you should use a space character constant:' '
. – Tansey