gpt4 book ai didi

c - C 中用字符串初始化的静态 char 数组

转载 作者:行者123 更新时间:2023-12-03 08:58:34 24 4
gpt4 key购买 nike

我试图理解我们在 C 讲座中得到的一段代码,但我不明白它的作用。

代码如下:

int main() {
static char *s[] = {"black", "white", "pink", "violet"};
char **ptr[] = {s+3, s+2, s+1, s}, ***p;
p = ptr;
++p;
printf("%s", **p+1);
return 0;
}

上面的代码打印了“ink”,但是它是如何工作的呢?

尝试

printf("s: %c\n",*s[0]);

给我'b'*s[1]返回'w'*s[2] 返回 'p' 等等。所以 *s 基本上返回它初始化的字符串的第一个字母。正在尝试

printf("s: %c\n",**ptr[0]);

返回v,因此*s看起来像这样:

{b,w,p,v}; 

但是,sizeof(s) 返回 16 而不是 4 并没有证实这一点。

所以我的问题是:这里发生了什么事?其余的字符存储在哪里?

最佳答案

你正在做

printf("s: %c\n",*s[0])  // this prints the character 'b'

如果您使用%s,您将获得整个字符串

printf("s: %s\n",s[0])

代码的逐行解释如下

static char *s[] = {"black", "white", "pink", "violet"};  
// Here s is an array of pointers to char.
// s[0] will point to "black", s[1] will point to "white" etc.
char **ptr[] = {s+3, s+2, s+1, s}, ***p;
//ptr is an array of pointer to pointer to char.
// ptr[0] will be equal to s+3, i.e. &s[3].
// ptr[1] will be &s[2]
// p is a pointer to pointer to a pointer. (triple pointer)
p = ptr; // p is set as the base addr of ptr.
++p; // p is incremented, i.e. it points to next element of ptr, i.e. ptr[1]
printf("%s", **p+1); // This is equivalent to (**p) +1
// p = &s[2]. therefore
// *p = s[2]
// **p = *(s[2]) --> **p points to the `p` character in pink
// **p +1 will point to the `i` character in `pink'. That is what is printed.
return 0;

关于c - C 中用字符串初始化的静态 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53006367/

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