2

在我的代码中,我必须将一个再见数组 (byte[] temp = null;) 传递给一个在其中分配并填充数据的函数。从函数返回后,它仍然为空。我怎样才能找到解决这个问题的方法。???请帮我。

  byte[] temp = null;
  ret = foo(temp);

  boolean foo(byte[] temp)
  {
      temp = new byte[];
      //fill array
  }
4

2 回答 2

8

你对你的代码不是很清楚,但如果我理解你的话,你有如下内容:

byte[] temp = null;
methodThatAllocatesByteArray(temp);
// temp is still null.

如果这是对您所说内容的正确理解,那么问题在于 temp 是对任何内容的引用。将该引用发送给另一个方法会生成该引用的副本(而不是使用相同的引用),因此,更改该引用(分配给参数变量)只会更改本地方法的引用。你需要做的是byte[]从这样的方法中返回一个新的:

public byte[] methodThatAllocatesByteArray() {
    // create and populate array.
    return array;
}

并这样称呼它:byte[] temp = methodThatAllocatesByteArray(). 或者您可以先初始化数组,然后将对该数组的引用传递给另一个方法,如下所示:

byte[] temp = new byte[size];
methodThatAllocatesByteArray(temp);

由于在这种情况下,参数 inmethodThatAllocatesByteArray将指向与 相同的数组temp,因此对其进行的任何更改(除了将其重新分配给不同的数组或 null 之外)都可以通过temp.

于 2012-09-19T13:26:51.697 回答
4

你需要使用这个:

 byte[] temp = new byte[some_const];
  ret = foo(temp);

  boolean foo(byte[] temp)
  {
      //fill array
  }

或者

 byte[] temp = null;
  temp  = foo(temp);

  byte[] foo(byte[] temp)
  {    temp = new byte[some_const];
      //fill array
      return temp;
  }
于 2012-09-19T13:26:33.447 回答