简体   繁体   中英

Passing array to a function Java v/s C

I am pretty new to Java and one topic just blew my mind. Passing array to a java function. Code is as follows:

private void PassArray(){
String[] arrayw = new String[4]; //populate array
PrintA(arrayw);
}

private void PrintA(String[] a){
//do whatever with array here
}

They say in java arrays are passed by reference. But it looks so much similar to "Call by Value" in C:

#include <stdio.h>

/* function declaration */
double getAverage(int arr[], int size);

int main ()
{
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
double avg;

/* pass pointer to the array as an argument */
avg = getAverage( balance, 5 ) ;

/* output the returned value */
printf( "Average value is: %f ", avg );

return 0;
}

double getAverage(int arr[], int size)
{
int    i;
double avg;
double sum;

for (i = 0; i < size; ++i)
{
sum += arr[i];
}

avg = sum / size;

return avg;
}

Please explain the difference between them in terms of value,reference and memory allocations. Any further links will be appreciated.

Arrays in C are "pass-by-reference" and not "pass-by-value". Please look at the following program:-

    void print_array (int array[], int len)
    {
        printf("Printing the array: ");
        int i;

        for (i = 0; i < len; ++i) {
            printf("%d ", array[i]);
        }

        printf("\n");
    }

    void populate_array (int array[], int len)
    {
        printf("Populating the array....\n ");
        int i;

        for (i = 0; i < len; ++i) {
            array[i] = i;
        }
    }


    int main() 
    {
        int array[5];
        memset(array, 0, sizeof(int) * 5);  

        print_array(array, 5);  
        populate_array(array, 5);
        print_array(array, 5);  

        return(0);
    }

    Output:-
    GAGUPTA2-M-40UT:Desktop gagupta2$ ./a.out 
    Printing the array: 0 0 0 0 0 
    Populating the array....
    Printing the array: 0 1 2 3 4 

So once you pass arrays as parameters to functions, it is no longer "pass-by-value" mechanism in C. It is "pass-by-reference". Hence, prior to calling populate_array(), the contents of the array were all zeros and after calling populate_array() they had some value.

In Java you will observe something similar. Putting a similar Java code below:-

    public class Test 
    {
        public static void print_array (String[] array)
        {
            System.out.println("Printing the array");

            for (int i = 0; i < array.length; ++i) {
                System.out.print(array[i] + " ");
            }

            System.out.println();
        }

        public static void populate_array (String[] array)
        {
            System.out.println("Populating the array");

            for (int i = 0; i < array.length; ++i) {
                array[i] = new String("init_array");    
            }
        }

        public static void main (String[] args) 
        {
            String[] array = new String[5];

            print_array(array);
            populate_array(array);
            print_array(array);
        }
    }

Output:-
GAGUPTA2-M-40UT:Desktop gagupta2$ java Test
Printing the array
null null null null null 
Populating the array
Printing the array

In java the primitive data types like int, float, double, boolean etc are always passed by value but when you pass non-primitive types like arrays, string and objects, the address of the object gets passed. See Is Java "pass-by-reference" or "pass-by-value"? for more details.

Arrays are allocated on the heap and they will be passed by reference. Compared to C they look like automatic variables and handling also looks like handling of automatic variable in C. Simply try to change array in method (function) and see what is happening. On the other side integer is allocated on the stack and is passed by value. Here are some typical manipulations, passing array as parameter to function and returning it from function.

public static void main(String[] args) {
  int[] arr = {0, 0, 0, 0};
  print(arr);
  load(arr);
  print(arr);
  print(generate(5));
  long s = 0;
  System.out.println("long is " + s);
}

void willItChange(long param){
  param = 3;
}
static int[] generate(int size){
  int[] arr = new int[size];
  for(int i = 0; i<size; i++)
    arr[i] = i + 1;
  return arr;
}

static void load(int[] arr){
  for(int i = 0; i<arr.length; i++)
    arr[i] = i + 1;
}

static void print(int[] arr){
  for(int i = 0; i<arr.length; i++)
    System.out.print(arr[i] + " ");
  System.out.println();
}

Execution should produce the following output

0 0 0 0 
1 2 3 4 
1 2 3 4 5 
long is 0

Arrays are passed by reference and long is passed by value.

In C:

In a sense, you cannot "pass arrays" in C, because it is impossible for a function to have a parameter of array type. The standard states that a function declaration containing a parameter declared to be of "array of T" type will be "adjusted" to be a parameter of "pointer to T" type. In your example above, the parameter arr has type int * (pointer to int ).

So what happens in the call expression getAverage( balance, 5 ) where balance is an array ( int [5] )? The compiler sees that the function expects a pointer type ( int * ) for that parameter, and then applies the implicit conversion from an array value into a pointer rvalue (a pointer to the first element of the array) before passing this pointer (to the parameter which expects a pointer). As you can see, there is no passing of "arrays".

Also, everything in C is pass-by-value. There is no pass-by-reference in C. The pointer-to- int you are passing is passed by value, ie its value (what it points to) is copied into a local copy in the function.

In Java:

In Java, arrays are objects and objects in Java are not values and cannot be "passed" (there are no "object types" in Java; only primitive types and reference types). Arrays, like all objects, can only be manipulated through "references" (pointers to objects).

Everything in Java is pass-by-value. There is no pass-by-reference in Java. In your example, you have a parameter a of type String[] , which is a reference type that can hold pointers to array-of- String objects. The pointer to array you are passing is passed by value, ie its value (what it points to) is copied into a local copy in the function.

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