简体   繁体   English

对字符串指针数组的打印过程感到困惑

[英]Confused about the printing procedure of array of pointers to string

#include<stdio.h>
int main(){
    char *names[2] = {"Lord", "Voldemort"};
    printf("%s %s\n",names[0], names[1]);
    return 0;
}

Why is the above code working? 上面的代码为什么起作用? I mean, it should print the addresses of the strings it is containing in their respective indexes and we should be using *names[0] and *names[1]. 我的意思是,它应该打印包含在它们各自索引中的字符串的地址,我们应该使用* names [0]和* names [1]。 But why it is working though? 但是为什么它能正常工作呢?

If you had an array of integers like 如果您有一个整数数组,例如

int values[2] = { 1, 2 };

then what would you get if use used eg values[1] ? 那么如果使用如values[1] ,会得到什么? You would get the second element in the array. 您将获得数组中的第二个元素 Printing this values array would be done like 打印此values数组将像

printf("%d %d\n", values[0], values[1]);

You are with me this far? 你到目前为止和我在一起吗?

Now back your array. 现在备份您的数组。 If you use names[1] what do you get then? 如果使用names[1] ,那么您会得到什么? You still get the second element in the array. 仍然会获得数组中的第二个元素 And what is the second element? 第二个要素是什么? It is a pointer to char (ie char * ). 它是char的指针(即char * )。 And what can a pointer to char be used as? 指向char的指针可以用作什么? A string . 一个字符串

And the "%s" format with printf expects a string, a char * more specifically. printf"%s"格式需要一个字符串,更具体地说是char * Which is just what you give as arguments. 这就是您提供的参数。


If you use the dereference operator like *names[1] then thanks to operator precedence it is equal to *(names[1]) which is equal to names[1][0] . 如果您使用像*names[1]这样的取消引用运算符,则由于运算符优先级的原因,它等于*(names[1]) ,等于*(names[1]) names[1][0] In other words it gives you the first character in the string pointed to by names[1] . 换句话说,它为您提供了names[1]指向的字符串中的第一个字符

names[0] and names[1] are both const char* types. names[0]names[1]都是const char*类型。

When you use %s with a const char* argument, printf outputs the characters starting at the beginning of the argument, until \\0 is reached. 当您将%sconst char*参数一起使用时, printf输出从参数开头开始的字符,直到达到\\0

If you want the addresses then use 如果您想要地址,请使用

printf("%p %p\n", (const void*)names[0], (const void*)names[1]);

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

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