Initialise and return a byte array in java

半城伤御伤魂 提交于 2019-12-10 11:46:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!