问题
In my code i have to pass a bye array (byte[] temp = null;) to a function which is allocated and filled with data inside it. After returning from function it is still null. How can i find a solution to this problem.??? Please help me.
byte[] temp = null;
ret = foo(temp);
boolean foo(byte[] temp)
{
temp = new byte[];
//fill array
}
回答1:
You need to use this:
byte[] temp = new byte[some_const];
ret = foo(temp);
boolean foo(byte[] temp)
{
//fill array
}
or
byte[] temp = null;
temp = foo(temp);
byte[] foo(byte[] temp)
{ temp = new byte[some_const];
//fill array
return temp;
}
回答2:
You're not very clear about your code, but if I understand you right, you have something like the following:
byte[] temp = null;
methodThatAllocatesByteArray(temp);
// temp is still null.
If this is a correct understanding of what you're saying, the problem is that temp is a reference to nothing. Sending that reference to another method makes a copy of that reference (rather than use the same reference), therefore, changing that reference (assigning to the parameter variable) only changes it for the local method. What you need to do is to return a new byte[]
from the method like this:
public byte[] methodThatAllocatesByteArray() {
// create and populate array.
return array;
}
and call it like this: byte[] temp = methodThatAllocatesByteArray()
. Or you can initialise the array first, then pass the reference to that array to the other method like this:
byte[] temp = new byte[size];
methodThatAllocatesByteArray(temp);
Since in this case the parameter in methodThatAllocatesByteArray
will point to the same array as temp
, any changes to it (other than reassigning it to a different array or null), will be accessible through temp
.
来源:https://stackoverflow.com/questions/12495619/initialise-and-return-a-byte-array-in-java