gpt4 book ai didi

C 代码中的 Java 数组

转载 作者:行者123 更新时间:2023-11-30 20:33:00 25 4
gpt4 key购买 nike

我正在学习 Java 数组,并且有 C/C++ 背景,我试图理解 Java 中数组的整个概念。由于Java中的所有内容都是指针,因此我知道即使数组也是指向对象(在本例中为数组对象)的指针,并且这些数组对象包含原始类型值(int [] ia)或指向对象的指针(String [] sa) ),因为我们不能像 C++ 那样操作对象,而只能操作堆上对象的引用。那么用 C 代码表示二维 Java 数组是否正确:

TYPE *(*(*aptr)[M])[N];

(*aptr) has type: TYPE *(*[M])[N] and is converted to: TYPE *(**)[N]
(*aptr)[m] has type: TYPE *(*)[N]
*(aptr)[m] has type: TYPE *[N] and is converted to: TYPE **
(*(*aptr)[m])[n] has type: TYPE *

so

TYPE obj = *(*(*aptr)[m])[n]) has type TYPE

我猜对了吗?

最佳答案

你漏掉了两点。 Java 数组知道它的类型和长度,因此它的 C 等效项将是一个结构体。 Java int[] 数组的粗略类比是(此解释并不意味着任何现有 JVM 使用此结构,它只是作为 Java 数组的 C 语言类比):

struct int_array {
TYPE *type; // This points to a description that we are an int[] array
int length;
int *data; // Allocated with malloc(length*sizeof(int))
};

然后,Java a[i] 会转换为 C a->data[i],如果 则抛出 ArrayIndexOutOfBoundsException i 位于 0...length-1 之外。

二维数组只是数组的数组,例如int[][] 可能看起来像:

struct two_dim_int_array {
TYPE *type; // This points to a description that we are an int[][] array
int length;
struct int_array *data; // Allocated with malloc(length*sizeof(struct int_array))
};

因此,b[i][j] 会转换为 b->data[i].data[j],并进行必要的范围和 null 检查。

关于C 代码中的 Java 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46407829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com