Home > Enterprise >  Question about array increment in c array[str]
Question about array increment in c array[str]

Time:10-28

Recently I found some code which I am trying to understand.

#include<stdio.h>
#include<string.h>

int main()
{
    int i;
    int arr[256]={0};

    char str[60]=" test test test TEST TEST TEST";

    for(i=0;i<strlen(str);i  )
    {
        if(!((str[i]==' ') ||(str[i]==',') ))
            arr[str[i]]  ;
    }

    printf("Repeated character in a string are:\n");
    for(i=0;i<256;i  )
    {
        if(arr[i]>1)
        {
            printf("%c occurs %d times\n",(char)(i),arr[i]);
        }
    }
}

The output is:

Repeated character in a string are:
E occurs 3 times
S occurs 3 times
T occurs 6 times
e occurs 3 times
s occurs 3 times
t occurs 6 times

My questions is regarding this line of code: arr[str[i]] ;.

How does this manage to store the total amount of times a character is used? What goes on inside computer memory regarding arr[str[i]] every loop?

Best regards,

CodePudding user response:

        arr[str[i]]  ;

Can be replaced with

char c = str[i];
arr[c]  ;

C is the character in the string. Each characters are only numbers for the computer. 'a' could equals to 0, or 12, it's all about conventions. The current convention here is named ascii. For example, the character 'a' is 97, the character 'A' is 65 in ascii. It's only a human convention.

Arr is an array initialized with 0s.

Let's say c here contains the letter 'a', so it contains 97. arr[c] ; simply increments the 98th value of the array

CodePudding user response:

arr is just an array of counters, where each counter corresponds to a symbol code in the token table.

A character can typically hold positive values up to 127, though in some cases up to 255. Therefore the size of arr was set to 256, to cover all cases. Arguably slightly wasteful since codes 0 to 31 are usually non-printable characters.

Since the array was set to all zeroes at start, every counter start at that.

When the program encounters for example 'A' it doesn't see a letter but the symbol code such as ASCII 65. It will then increase the counter on index 65 with 1.

So arr[str[i]] would mean: take the letter inside str[i], which is really just a number such as 65, then increase array index 65 by 1.

  • Related