gpt4 book ai didi

c++ - 代码中*的含义

转载 作者:太空宇宙 更新时间:2023-11-04 15:35:34 25 4
gpt4 key购买 nike

我遇到过如下代码

bool* keyStates = new bool[256];
void keyPressed(unsigned char key, int x, int y) {
keyStates[key] = true; // Set the state of the current key to pressed
}

其中有一个问题要问我。 如您所见,key 是一个char,因此它的值类似于'a'keyStates 是一组指向 bool 变量的指针。

因此,我不明白为什么像 keyStates['a'] 这样的东西应该是真的?

在我看来,它就像一个关联数组。对吧?

最佳答案

每个字符都由一个唯一的数字表示,具体取决于表示1。这个唯一的数字表示用作动态分配的 bool 数组 keyStates[] 中的索引,在您的例子中:

char key = 'a';
keyStates[key] = true;

意味着将索引为 97 的元素设置为 true。实际上,所有字符都是数组元素的唯一键/索引。

现在,回答你的问题:

Therefore, I cannot understand why something like keyStates['a'] should be true?

char 的定义中,有一段写着:

char: Smallest addressable unit of the machine that can contain basic character set. It is an integer type. Actual type can be either signed or unsigned depending on the implementation.

因此,一个char是一个小整数,它是一个类似于整数的相同整数(或指针)算法。

注意事项:

该函数的参数是unsigned char,因为这种类型的变量的值在0255之间,而signed char(即char) 的值介于 -128127 之间,未覆盖数组的所有索引并且可能访问数组之外​​的内存。


1。 ASCII (extended ASCII)是一个示例,其中所有字符都用从 0255 的值表示。

关于c++ - 代码中*的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34842253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com