Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hardcode byte array in C

Tags:

arrays

c

syntax

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.

like image 400
Eric Avatar asked May 19 '09 16:05

Eric


People also ask

What is a byte array in C?

byte array in C An unsigned char can contain a value from 0 to 255, which is the value of a byte. In this example, we are declaring 3 arrays – arr1, arr2, and arr3, arr1 is initialising with decimal elements, arr2 is initialising with octal numbers and arr3 is initialising with hexadecimal numbers.

Can you print [] byte?

You can simply iterate the byte array and print the byte using System. out. println() method.

What is a byte array?

A byte array is simply an area of memory containing a group of contiguous (side by side) bytes, such that it makes sense to talk about them in order: the first byte, the second byte etc..

What is the default value of byte array in C#?

The default values of numeric array elements are set to zero, and reference elements are set to null. Since byte represents integer values from 0 to 255 , all elements are set to 0 in your authToken array.


5 Answers

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
like image 178
Adam Rosenfield Avatar answered Oct 19 '22 19:10

Adam Rosenfield


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.

like image 44
quinmars Avatar answered Oct 19 '22 21:10

quinmars


Try with:

char myArray[] = { 0x00, 0x11, 0x22 };
like image 40
jbradaric Avatar answered Oct 19 '22 19:10

jbradaric


Doesn't

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

work?

like image 39
Tom Avatar answered Oct 19 '22 20:10

Tom


  • Array Initialization

  • Array Initialization

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

like image 24
none Avatar answered Oct 19 '22 21:10

none