简体   繁体   中英

Passing array as an argument: C and Java

Before I ask my question, I will note that I know:

  1. In C, we can call a method by value as well by reference
  2. In Java, we can only call a method by value ( when we pass an Object, we are passing the value of the object reference not the object reference itself )
  3. In C and Java context, there is a difference between pointers and reference.

Now to the question:

Consider an array:

arr = {1,2,3,4,5} //len =5

In C, I can do the following two things:

foo(arr, len);
bar (arr+ 2, len -2);

Function definitions:

foo(int *a, int l) {
  ...
  printf("%d", &a[0];  //prints 1
  ...
}

bar (int *a, int l){
  printf("%d", &a[0];  //prints 3
  ...
}

As we can see array a in function bar starts with the value 3, as it contains the address of arr[2](the original array). This is a neat way of passing arrays in C, if we want to treat a sub-array as a new array with starting index 0.

I was wondering if same can be achieved in Java not withstanding that the following call has different meanings in C and Java:

foo(arr);

yes, just add a parameter int off or use the IntBuffer class.

void foo(int[] a,int off, int l) {
 ...
 System.out.printf("%d", a[off];  //prints 1
 ...
 ...
}

f(a,2,l);


void foo(IntBuffer a,int l){
   System.out.printf("%d",a.get(0));
}
IntBuffer buffer = IntBuffer.wrap(a,2,a.length-2);
foo(buffer,l);

If your question is about whether you can address the elements of the array by doing pointer arithmetic like in arr + 2 , then the answer is no.

However, you can achieve the same effect by passing in the array and the position where you want start reading the array.

The underlying structure of the array in java has an extra element at the head that indicates it's length. So your original array would be {len, 1, 2, 3, 4, 5} as stored by the JVM. This is done to keep java 'safe' from out of index operations on the array. This also makes it almost impossible to do pointer arithmetic in java.

To do something like this in java you would typically use some sort of Buffer class to wrap your array.

Java缺乏本机切片功能(就像C中关于数组开始的隐式函数或几种现代语言中的显式函数),但是很容易构建自己的类,该类包装数组,索引和长度你需要它。

The idea is the same when you pass arrays in C and Java.

In Java, all that are passed for objects are references to them, namely pointers. In Java, you never say: A *a = new A(); you just write A a = new A(); The lack of * is the difference. Otherwise, A behaves exactly like a pointer.

Primitive variables are passed by value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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