简体   繁体   English

在C ++中通过char访问数组

[英]Accessing array by char in C++

Usually, I access an array in C++ by the syntax foo[2] , where 2 is the index of an array. 通常,我使用foo[2]语法访问C ++中的数组,其中2是数组的索引。

In the below code. 在下面的代码中。 I didn't understand how this code is giving output and access this array by index 'b' , 'c' . 我不明白这段代码如何给出输出并通过索引'b''c'访问该数组。 I am confused it is array index or something else. 我很困惑它是数组索引或其他。

int count[256] = {0};
count['b'] = 2;
cout << count['b'] << endl; //output 2
cout << count['c'] << endl; //output 0

Output 输出量

2
0

Type char is actually an integral type. char类型实际上是整数类型。 Every char value represented by a character literal has an underlying integral value it corresponds to in a given code page, which is probably an ASCII table . 字符文字表示的每个char值都有一个对应于给定代码页(可能是ASCII表)中的基础整数值。 When you do: 当您这样做时:

count['b'] = 2;

you actually do: 您实际上是这样做的:

count[98] = 2;

as character 'b' corresponds to an integral value of 98 , character 'c' corresponds to an integral value of 99 and so on. 因为字符'b'对应于98的整数值,字符'c'对应于99的整数值,依此类推。 To illustrate, the following statement: 为了说明,下面的语句:

char c = 'b';

is equivalent of: 等价于:

char c = 98;

Here c has the same underlying value, it's the representation that differs. 这里c具有相同的基础值,只是表示形式有所不同。

Remember that in c++ characters are represented as numbers. 请记住,在c ++中,字符以数字表示。 Take a look at this ascii table. 看一下这张ASCII表。 http://www.asciitable.com http://www.asciitable.com

According to this the character 'b' is represented 98 and 'c' as 99. Therefore what your program is really saying is... 据此,字符“ b”表示为98,而“ c”表示为99。因此,您的程序真正要说的是...

int count[256] = {0};
count[98] = 2;
cout << count[98] << endl; //output 2
cout << count[99] << endl; //output 0

Also incase you don't know saying an array = {0} means zero initialize every value so that is why count['c'] = 0 . 另外,如果您不知道说数组= {0}意味着将每个值初始化为零,这就是为什么count['c'] = 0

In C/C++ there is not 8 bit / 1 byte integer. 在C / C ++中,没有8位/ 1个字节的整数。 We simply use the char type to represent a single (signed or unsigned) byte and you can even put signed and unsigned infront of the char type. 我们仅使用char类型来表示单个(有符号或无符号)字节,您甚至可以将有符号和无符号放置在char类型的前面。 Char really is just another int type which we happen to use to express characters. Char实际上只是我们用来表达字符的另一种int类型。 You can also do the following. 您还可以执行以下操作。

char b = 98;
char c = 99;
char diff = c - b; //diff is now 1

Because characters are always represented by integers in the computer, it can be used as array indices. 由于字符在计算机中始终由整数表示,因此可以将其用作数组索引。

You can verify by this: 您可以通过以下方式进行验证:

char ch = 'b';
count[ch] = 2;
int i = ch;
cout << i << endl;
cout << count[i] << endl;

Usually the output is 98 2 , but the first number may vary depending on the encoding of your environment. 通常输出为98 2 ,但是第一个数字可能会根据您环境的编码而有所不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM