C 中的下标数组

Elj*_*jay 1 c arrays

是否可以在 C 中创建一个下标数组,该数组使用另一个数组作为其索引。我浏览了一个链接:IDL — Using Arrays as Subscripts

数组可以用作其他数组的下标。下标数组中的每个元素选择下标数组中的一个元素。

再举一个例子,考虑以下语句:

A = [6, 5, 1, 8, 4, 3]  
B = [0, 2, 4, 1]  
C = A[B]  
PRINT, C  
Run Code Online (Sandbox Code Playgroud)

这会产生以下输出:

6       1       4       5  
Run Code Online (Sandbox Code Playgroud)

以上在 C 编程中是否可行。

leg*_*s2k 5

数组可以用作其他数组的下标。下标数组中的每个元素选择下标数组中的一个元素。

从语法上讲,这在 C 中是不可能直接实现的。您必须使用循环来实现这一点。

int a[] = {6, 5, 1, 8, 4, 3};
int b[] = {0, 2, 4, 1};
for (int i = 0; i < (sizeof(b)/sizeof(b[0])); ++i)
    printf("%d\n", a[b[i]]);
Run Code Online (Sandbox Code Playgroud)

如果你真的想让它看起来那么整洁,那么把它包装在一个函数中,你应该没问题:

// returns the no. of elements printed
// returns -1 when index is out of bounds
int print_array(int *a, int *b, size_t na, size_t nb)
{
    int i = 0;
    for (i = 0; i < nb; ++i)
    {
        int const index = b[i];
        if (index >= na)
            return -1;
        print("%d\n", a[index]);
    }
    return i;
}
Run Code Online (Sandbox Code Playgroud)