You can do the same thing in C, but you should declare it of type char[], not char*, so that you can get its size with the sizeof operator:
char myArray[] = { 0x00, 0x11, 0x22 };
size_t myArraySize = sizeof(myArray); // myArraySize = 3
Answer from Adam Rosenfield on Stack OverflowYou can do the same thing in C, but you should declare it of type char[], not char*, so that you can get its size with the sizeof operator:
char myArray[] = { 0x00, 0x11, 0x22 };
size_t myArraySize = sizeof(myArray); // myArraySize = 3
Just for the sake of completeness, with C99 you can also use compound literals:
char *myArray = (char []) {0x00, 0x11, 0x22 };
If source code compatibility to C++ is a requirement, you better don't use this construct, because it is - afaik - not part of the C++ standard.
initialization - Initialize C array with bytes and string literals - Stack Overflow
Looking for method to initialize an array of structures (type contains some constant vectors)
How to create a byte array in C++? - Stack Overflow
Initializing a vector<BYTE> from existing BYTE array - Post.Byes
You will have to initialise the byte array using a function like this:
uint8 *initByteArray(const struct foo *foo)
{
unsigned slen = foo->string ? strlen(foo->string) : 0;
assert(slen <= 255);
uint8 *array = malloc(slen + 3);
unsigned i = 0;
array[i++] = foo->param1;
array[i++] = (uint8)slen;
if (slen) {
strncpy(&array[i], foo->string, slen);
i += slen;
}
array[i++] = foo->param2;
return array;
}
If the struct contains any integers with a length greater than 1 (i.e. uint16, etc) then you will also need to consider their endianness during encoding.
C allows string literals (also in initialisers) to be broken up; the compiler will paste them for you.
So, you could do:
char unit1[8] = "\x40" "\x05" "Hello" "\x3e";
char unit2[9] = "\x40" "\x06" "World!" "\x3e";
char unitBoth[] = "\x40" "\x05" "Hello" "\x3e"
"\x40" "\x06" "World!" "\x3e";
The unitBoth[] array has no defined size; it is just one byte longer (the nul byte) than the sum of the two separate arrays.
#include <stdio.h>
#include <string.h>
int main(void)
{
unsigned idx, len;
printf("Unit1 Size = %zu\n", sizeof unit1);
for (idx=0; idx < sizeof unit1; idx++) {
printf("%u : %02x\n" , idx , 0xff & unit1[idx] );
}
printf("\nUnit2 Size = %zu\n", sizeof unit2);
for (idx=0; idx < sizeof unit2; idx++) {
printf("%u : %02x\n" , idx , 0xff & unit2[idx] );
}
printf("\nUnitBoth Size = %zu\n", sizeof unitBoth);
for (idx=0; idx < sizeof unitBoth; idx++) {
printf("%u : %02x\n" , idx , 0xff & unitBoth[idx] );
}
return 0;
}
And of course you could create a program or script to generate the definitions. (and include them in your main program, possibly in global scope)
First post here, old-school C user for microcontrollers (using GCC in Eclipse-based SDK published by ST Micro).
I need to create and initialize an array of structures (these structures would end up in RAM, so not using the const declaration anywhere.
Each element (a structure) would contain a few integers and a few byte arrays (one expressed as ASCII characters, others are 8-bit integers.) Currently I create the structure (individual elements) and call a function to copy the elements into the structure which is one of N in an array, which is probably OK but makes the source code look clumsy(er).
This is roughly what I'd like to accomplish, but not sure how to code in C (please forgive the formatting and I suspect none of this would compile, but hopefully it conveys what I'm trying to accomplish.
this is one element of the example struct array:
struct a_type
{
uint8_t x;
uint8_t[8] y;
uint8_t[8] z;
}
This is the array of the structures (eight of these, for example:)
a_type structs[8]; // End up with eight of the above, each containing one byte scalar and two byte arrays of 8 elements each.
What I want to accomplish looks like this:
structs[0].x = 123; // Single uint8_t
structs[0].y = "ABCDEFGH"; // Each char/uint8_t, no zero terminator
structs[0].z = { 0, 1, 2, 3, 4, 5, 6, 7}; // Each are uint8_t
Grateful for any suggestions, requests for clarification, or criticism!
DaveTry
class MissileLauncher
{
public:
MissileLauncher(void);
private:
unsigned char abc[3];
};
or
using byte = unsigned char;
class MissileLauncher
{
public:
MissileLauncher(void);
private:
byte abc[3];
};
**Note: In older compilers (non-C++11) replace the using line with typedef unsigned char byte;
If you want exactly one byte, uint8_t defined in cstdint would be the most expressive.
http://www.cplusplus.com/reference/cstdint/
Arrays cannot be assigned. You can only initialize them with the braces.
The closest you can get, if you want to "assign" it later, is declaring another array and copying that:
const int array_size = 4;
char a[array_size] = {}; //or {0} in C.
char b[array_size] = {0xb4,0xaf,0x98,0x1a};
std::copy(b, b + array_size, a);
or using the array class from std::tr1 or boost:
#include <tr1/array>
#include <iostream>
int main()
{
std::tr1::array<char, 4> a = {};
std::tr1::array<char, 4> b = {0xb4,0xaf,0x98,0x1a};
a = b; //those are assignable
for (unsigned i = 0; i != a.size(); ++i) {
std::cout << a[i] << '\n';
}
}
What Ben and Chris are saying is.
byte test[4]={0xb4,0xaf,0x98,0x1a};
If you want to do it at run time, you can use memcpy to do the job.
byte startState[4]={0xb4,0xaf,0x98,0x1a};
byte test[4];
memcpy(test, startState, sizeof(test));
The ArraySegment<T> structure provides a view of an array without creating a copy. It cannot be used in places where a byte array is expected, though.
ArraySegment<byte> myArraySegment = new ArraySegment<byte>(myArray, 2, 5);
If you need a byte array, you need to copy the desired values to a new array instance, preferably using Buffer.BlockCopy:
byte[] newArray = new byte[5];
Buffer.BlockCopy(myArray, 2, newArray, 0, 5);
This is possible, but it requires unsafe code:
unsafe
{
byte[] b = new byte[buffersize];
fixed(byte* bStart = b)
{
byte* header = bStart + 5;
byte* data = bStart + 25;
}
}
That being said, this is generally avoided unless absolutely necessary in C#. Using unsafe code is not the norm because it is, as suggested, not safe. This type of code can lead to many bugs, so it's best to rethink the design.
How come this works:
Char name[20] = "Mary";
But this doesn't.
Char name[20];
Name[20] = "Mary";
Am I correct in that the above fails because I'm telling it to put "Mary" in the name[20] element? Is that how it's interpreted?
Is there a way to initialize char name[20] array separately from the declaration without using srtcpy()? Just wondering
Thanks
I came across an issue where a char array wasn't initialised and the fix was to put "" into the value e.g. Char array [100] = "";
I don't get why this worked, i suspect it was just filling with garbage before, so i have looked online for some good explanations but have only come across a tonne of articles explaining assigning string literals to the array inside curly braces.
Are there any good resources explaining the different ways we can initialize arrays? I know a few but am definitely missing some.l and a complete list would be excellent.
Thankyou