有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java理解C中声明的数组指针算法

我正在尝试将一些C代码转换成另一种语言(例如:Java或C#)。问题在于了解这些数组是如何声明和使用的

这是演示我的问题的最低代码:

static void some_function ( )
{
    int16_t arr_tmpShort[120 + 40], *ptr0, *ptr1;
    int offset = 5;
    
    //assume that "arr_tmpShort" is now filled with some values
    ptr0 = arr_tmpShort + 84 - offset;
    ptr1 = arr_tmpShort + 85;

}

所以我需要第二种意见:

这一行:

int16_t arr_tmpShort[120 + 40]; 

正在创建一个数组,用于存放160个空头条目。那个plus符号除了简单的算术之外没有什么特别的作用,对吗

问题:现在这些行

    ptr0 = arr_tmpShort + 84 - offset;
    ptr1 = arr_tmpShort + 85;

很奇怪,因为我看到的是数组上的算术运算
这对我来说是新的,经过一些研究,我需要澄清以下哪一项更有效或更真实

  • ptr0 = arr_tmpShort + 84等于Java/C#asarr_tmpShort[84](数组中的一个位置)
  • 它被认为是ptr0 =
    • 或者(arr_tmpShort[84] - offset); //get [84] Short value and minus it by offset
    • 还是(arr_tmpShort[84 - offset]); //get [84 - offset] Short value from array

共 (2) 个答案

  1. # 1 楼答案

    C指针算法:https://www.tutorialspoint.com/cprogramming/c_pointer_arithmetic.htm

    ptr0 = arr_tmpShort + 84 is equal to Java/C# as arr_tmpShort[84] (a position in array)?

    不会。它计算所需的地址,但实际上不访问值(读或写)

    Is it considered as ptr0 = or (arr_tmpShort[84 - offset]); //get [84 - offset] Short value from array?

    它离这个最近,但同样无法访问元素。已经计算了arr_tmpShort[84-offset]的地址,但还没有进行访问

    要访问元素,通常必须取消对变量的引用

    ptr0 = arr_tmpShort + 84;
    short x = *ptr0;     // this retrieves the 84th element, assuming a short
    
  2. # 2 楼答案

    1)是的,编译器很可能会将其优化到160

    2)在c语言中,可以将数组和指针视为同一事物。 所以,当你有i[3]这样的代码时,这相当于写*(i+3)。这两个函数都返回数组i开始后存储在第三个内存位置的元素的值。More information on pointers can be found here

    所以ptr0 = arr_tmpShort + 84 - offset将等于arr_tmpShort[84 - offset]的内存位置,在本例中是arr_tmpShort[79]

    稍后您还可以编写*ptr0,如果没有进行其他修改,它将等于arr_tmpShort[79]