1

鉴于 C 中的以下声明,我可以将“+”应用于地址,并访问其他元素。

char toto[5];

换句话说,应用此运算符 +

toto+0x04

在 Java 中访问不同的数组元素。

是否有另一种方法可以在 java 中实现此操作?

非常感谢

4

4 回答 4

3

如果我是对的,您想访问数组中该位置的元素。你可以在java中做到这一点。

char foo[] = new char[]{'1', '2','3','4', '5'};
char fooAtPositionFour = foo[4];

并以这种方式分配一个新值:

foo[4] = 'x';
于 2012-08-01T13:55:29.937 回答
2

从技术上讲不是,因为 toto+4 是一个地址,Java 的内存管理策略与 C 的完全不同。但是,您可以使用 toto[4] 获得 *(toto+4) ;)

于 2012-08-01T13:53:54.150 回答
1

Almost always there is another way in java to implement what you want.

You rarely process char[] directly. Using String and StringBuilder is preferred.

String toto = "hello";
String lastChar = toto.substring(4); // from the 4th character.

To answer your question literally. You can use the sun.misc.Unsafe with get/putByte or get/putChar class to do pointer arithmetic, but I suggest avoiding it unless you really, really need to.

于 2012-08-01T15:02:27.710 回答
1

实际上我需要隔离最后四个字节,其中 param 是 char[]

您需要最后四个字节还是最后一个字符?最后一个字符toto[toto.length-1]

对于最后四个字节,您需要将 char 数组(Java 中的 UTF-16,我不知道 C 中的编码是什么)转换为字节数组,然后取最后四个字节。

new String(toto).toBytes("THE_CHAR_ENCODING_YOU_WANT_TO_USE")
于 2012-08-01T15:16:41.553 回答