Eljay
Eljay

Reputation: 951

Subscripted arrays in C

Is it possible to create a subscripted array in C which uses another array as its indexes. I went through a link: IDL — Using Arrays as Subscripts

Arrays can be used as subscripts to other arrays. Each element in the subscript array selects an element in the subscripted array.

For another example, consider the statements:

A = [6, 5, 1, 8, 4, 3]  
B = [0, 2, 4, 1]  
C = A[B]  
PRINT, C  

This produces the following output:

6       1       4       5  

Is the above possible in C programming.

Upvotes: 1

Views: 2297

Answers (4)

legends2k
legends2k

Reputation: 32964

Arrays can be used as subscripts to other arrays. Each element in the subscript array selects an element in the subscripted array.

Syntactically this is not directly possible in C. You've to use a loop to achieve this.

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]]);

If you really want it to look that neat, then wrap it in a function and you should be alright:

// 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;
}

Upvotes: 5

Wary
Wary

Reputation: 1

No, that's not possible! In C, the array operator [x] is just a shorthand for a pointer addition. So a[x] is the same as (a+x)* This means the only valid arguments for the array operator are Integers.

Upvotes: 0

Purag
Purag

Reputation: 17071

The array index operator in C can only take integer arguments. This is because the compiler will expand the operation, like A[0], into a basic addition and dereference. As such, you can't pass an array as the operand to extract several indices from the original array.

Remember that A[0] is the same as *A, and A[1] is the same as *(A + 1), etc.

Upvotes: 1

moffeltje
moffeltje

Reputation: 4659

Yes ofcourse it is:

int a[6] = { 6, 5, 1, 8, 4, 3 };
int b[4] = { 0, 2, 4, 1 };

printf("\na[b[0]]=%d", a[b[0]]);
printf("\na[b[1]]=%d", a[b[1]]);
printf("\na[b[2]]=%d", a[b[2]]);
printf("\na[b[3]]=%d", a[b[3]]);

output:

a[b[0]]=6 a[b[1]]=1 a[b[2]]=4 a[b[3]]=5

Upvotes: 0

Related Questions