Converting Arrays / Pointers from C to Java

I am trying to rewrite a program in C in java. I have no experience in C, but some of them are in C ++, so I understand some things of a pointer / array. I'm a little confused though ... I am assigned the following code in C:

void ProcessStatus(Char *Stat){ DWORD relayDate; DWORD APIDate; version3=false; version4=false; version9=false; tiltAngle = false; ver4features=0; tooNew=false; ProgRev=0; switch(Stat[14]){ 

From what I understand, a pointer to char is passed to the ProcessStatus function; and I assume that the last line of code represented by Stat[14] calls it inside the array.

So I'm confused about how to pass a pointer to a char inside an array in Java.

Any help would be appreciated, even if it helps me understand the C code. Thanks.

+4
source share
4 answers

It is difficult to say whether a string or raw data was transmitted.

In the case of a string, use the built-in Java String class.

 void ProcessStatus( String stat) { ... switch ( stat.charAt( 14 ) ) { } } 

In case of raw data array use byte array

 void ProcessStatus( byte[] stat) { ... switch ( stat[ 14 ] ) { } } 

BTW, C char data type converted to byte type in Java. char type in Java denotes a 2-byte UTF-16 character. byte is exactly what it is (8 bit signed).

+4
source

Since C does not have a built-in String type, String in C is represented as an array of characters. Passing a pointer to a null element in an array is equivalent, in C, to passing a reference to an array, which I think this code does. Essentially replace char * Stat with String Stat and the switch (Stat [14]) with the switch (Stat.charAt (14))

+2
source

First, just to clarify, this is not a char , but a char ; char with capital C is a user-defined type. It could just be a typedef for char , otherwise it could be something else; We do not know.

Secondly, what is passed to the method is apparently a pointer to the first element of the char object block. The closest equivalent is a Java array, but depending on how you do it, you can completely leave the data structure in C, pass a pointer as long in Java, and let Java manipulate it by calling your own functions that you provide. A Java array is very different from a "array" or sequence of adjacent objects in C.

+2
source

In most cases, when you see char * (I don't know what your original Char ) in C or C ++, the Java equivalent would be String or char[] . The first is a string class, the last is an array of characters.

An equivalent function signature using String will look like this; we use charAt to access the 15th character:

 void ProcessStatus(String Stat){ // ... switch (Stat.charAt(14)) // ... } 

The equivalent with char[] will look like this (and as it is an array, we index it the same way you do with char * or char[] in C):

 void ProcessStatus(char[] Stat){ // ... switch (Stat[14]) // ... } 
+2
source

All Articles