2D数组空指针异常

huangapple go评论70阅读模式
英文:

2D array NullPointerException

问题

我在尝试将值存储在一个二维数组中时遇到了NullPointerException

int length = red[0].length;
int[][] sums = new int[length][];

for (int i = 0; i < length; i++) {
    int total = 0;
    for (int j = 0; j < length; j++) {
        int val = red[i][j];
        total = val + total;
    }
    sums[0][i] = total;
}

如果我将total存储在一个一维数组中,它可以正常工作。有人能告诉我为什么会出现这个错误吗?

英文:

I am getting a NullPointerException when trying to store a value in a 2D array:

int length = red[0].length;
int[][] sums = new int[length][];

for (int i = 0; i &lt; length; i++) {
    int total = 0;
    for (int j = 0; j &lt; length; j++) {
        int val = red[i][j];
        total = val + total;
    }
    sums[0][i] = total;
}

It works fine is I store total in a 1D array. Can anyone tell me why it's giving me this error?

答案1

得分: 0

我认为内部的数组和也应该有一定的容量。例如:

int[][] sums = new int[length][length];

否则,您正在访问sum[0][i],但是无法在索引i处访问内部数组。

英文:

I belive that inner array of sums should also have certain capacity. For example:

int[][] sums = new int[length][length];

Otherwise you are accessing sum[0][i] but inner array can’t be accessed at index i.

huangapple
  • 本文由 发表于 2020年10月9日 11:21:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/64273497.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定