Tutorial :hardcode byte array in C



Question:

I'm debugging a network application.

I have to simulate some of the data exchanged in order for the application to work. In C++ you can do something like

char* myArray = { 0x00, 0x11, 0x22 };  

However, I can't seem to find a C equivalent for this syntax.

Basically I just want to fill an array with hard coded values.


Solution:1

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  


Solution:2

Try with:

char myArray[] = { 0x00, 0x11, 0x22 };  


Solution: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.


Solution:4

Doesn't

char myArray[] = {0x00, 0x01,0x02};  

work?


Solution:5


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »