user8814070
user8814070

Reputation:

Can an array in C be indexed by a character?

void shifttable(char p[]) {
    int i, j, m;
    m = strlen(p);
    for (i = 0; i < MAX; i++)
        t[i] = m;
    for (j = 0; j < m - 1; j++)
        t[p[j]] = m - 1 - j;
}

I think, t[p[j]]=m-1-j; part, is indexed using a character. Can someone explain me how its actually working?

Upvotes: 0

Views: 213

Answers (4)

chqrlie
chqrlie

Reputation: 144989

char is an integral type. It can be used as an index value for the [] operator. Note however that t['0'] is not the same element as t[0]. The value of '0' depends on the encoding used on the platform. Most environments use ASCII for the source and execution character sets, where '0' has the value 48.

Indexing through character values is useful for many algorithms, especially searching and word matching. Typical implementations of the functions in <ctype.h> use arrays of 257 entries (or sometimes 384 entries for safety) where the function argument is used as an index.

Yet there is a major problem in using char values an index variables: the char type can be signed or unsigned by default, so the range of its values can encompass negative values. In the code fragment, if t is an array or a pointer to the beginning of an array, any character in p with a negative value will cause an access outside the boundaries of the array, which has undefined behavior.

It is advisable to raise the warning level so the compiler diagnoses such uses that are well hidden potential bugs. Use gcc -Wall or clang -Weverything.

To avoid this potential problem, the code should be modified this way:

#define MAX 256
int t[MAX];
void shifttable(char p[]) {
    int i, j, m;
    m = strlen(p);
    for (i = 0; i < MAX; i++)
        t[i] = m;
    for (j = 0; j < m - 1; j++)
        t[(unsigned char)p[j]] = m - 1 - j;
}

Note also that i, j, m and the t array should have type size_t to handle strings longer than INT_MAX.

Upvotes: 0

ivand58
ivand58

Reputation: 811

p[j] returns the ascii code of j-th character in p[], which is used later as index in t (the ascii code is extended to int by the compiler, see integer promotions).

Upvotes: 0

Vasanth Alagiriswamy
Vasanth Alagiriswamy

Reputation: 94

The character will be converted to equivalent ascii value and it acts as an index to an array. Below piece of code gives you an example,

void main()
{
   int a[10];

   a['\t'] = 10;

   printf("%d\n",a[9]);
}

Output: 10

Here ascii value of tab is 9 so a[9] will be 10. Please refer https://www.asciitable.com/ for decimal and hex equivalent of character.

Hope it helps you.

Upvotes: 0

R Sahu
R Sahu

Reputation: 206707

The array indexing operator is treated as *(arr + index).

When one operand of the binary + operator is a pointer, the other operand must be an integral type.

char is an integral type.

Hence,

t[p[j]] = m-1-j;

is a legal statement.

Upvotes: 1

Related Questions