gpt4 book ai didi

c - 在 C 中,像 "a string"[4] 这样的东西究竟意味着什么?

转载 作者:太空宇宙 更新时间:2023-11-04 00:49:05 24 4
gpt4 key购买 nike

以下摘自Mike Banahan的C书(Link: Section 2.8.1.5)

我知道 "a string" 简化为指向存储在内存中某处的该字符串的第一个字符的指针。但是我对 "a string"[4] 一无所知,而且书中给出的内容对我来说有点不清楚。

当字符串有 9 个字符时,大小如何为 4?除此之外,"a string"[0] 会引用第一个字符,"a string"[2] 会引用第三个字符,依此类推吗?如果不是,请您用简单的术语解释一下这本书的语法是什么意思?

让我难受的是“The first results in an类型为char,值为内部的表达式 字母“r”的表示。“r”从哪里来?

这是从那本书中摘录的文字:

Strings are implemented as arrays and although it might look odd, it is entirely permissible to use array indexing on them:

 -  "a string"[4]
- L"a string"[4]

are both valid expressions. The first results in an expression whose type is char and whose value is the internal representation of the letter ‘r’ (remember arrays index from zero, not one). The second has the type wchar_t and also has the value of the internal representation of the letter ‘r’.

注意:请忽略有关宽字符部分的内容,因为我认为这不相关。谢谢。

最佳答案

你可以拼出 "a string"[4] 如下:

char *s = "a string";
char ch = s[4];

它让事情变得更清楚了吗?

s[0]: a
s[1]:
s[2]: s
s[3]: t
s[4]: r
s[5]: i
s[6]: n
s[7]: g
s[8]: \0

关于c - 在 C 中,像 "a string"[4] 这样的东西究竟意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25956517/

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