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

时间:2018-10-26 10:09:36

标签: c arrays string static char

我试图用我在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; 
}

上面的代码打印“墨水”,但是它如何工作?

尝试

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不能确认这一点。

所以我的问题是:这是怎么回事?其余字符存储在哪里?

1 个答案:

答案 0 :(得分:2)

您正在做

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;