简体   繁体   English

如何在Java中通过指针算法访问数组元素

[英]How to access array elements by pointer arithmetic in Java

Given the following declaration in C, I can apply '+' to the address, and access other elements. 给定C语言中的以下声明,我可以将'+'应用于地址,并访问其他元素。

char toto[5];

In other words, applying this operator + 换句话说,应用此运算符+

toto+0x04

Accesses a different array element in Java. 访问Java中的其他数组元素。

Is there another way to implement this operation in java ? 还有另一种方法可以在Java中实现此操作吗?

Many Thanks 非常感谢

If I'm right you want to access the element at that position in the array. 如果我是对的,您想访问数组中该位置的元素。 You can do this in java. 您可以在Java中执行此操作。

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

and assign a new value this way: 并通过以下方式分配新值:

foo[4] = 'x';

Technically no since toto+4 is an address and Java's memory management policy is quite different from C's one. 从技术上讲,因为toto + 4是地址,并且Java的内存管理策略与C的策略完全不同,所以没有。 However you can get *(toto+4) with toto[4] ;) 但是,您可以通过toto [4]获得*(toto + 4);)

in fact i need to isolate the last four byte where param is a char[] 实际上,我需要隔离参数param是char []的最后四个字节

Do you need the last four bytes, or the last char? 您是否需要最后四个字节或最后一个字符? The last char then toto[toto.length-1] 然后最后一个字符toto[toto.length-1]

For the last four bytes you would need to turn the char array (UTF-16 in Java, I've no idea what the encoding would be in C) into a byte array then take the last four bytes. 对于最后四个字节,您需要将char数组(Java中的UTF-16,我不知道C语言中的编码)转换为字节数组,然后获取最后四个字节。

new String(toto).toBytes("THE_CHAR_ENCODING_YOU_WANT_TO_USE")

Almost always there is another way in java to implement what you want. Java几乎总是有另一种方式来实现所需的内容。

You rarely process char[] directly. 您很少直接处理char[] Using String and StringBuilder is preferred. 首选使用String和StringBuilder。

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. 您可以将sun.misc.Unsafe与get / putByte或get / putChar类一起使用来进行指针运算,但是除非您确实需要,否则我建议避免使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM