在C印花指针 [英] Printing pointers in C
问题描述
我想了解的指针的东西,所以我写了这个code:
I was trying to understand something with pointers, so I wrote this code:
#include <stdio.h>
int main(void)
{
char s[] = "asd";
char **p = &s;
printf("The value of s is: %p\n", s);
printf("The direction of s is: %p\n", &s);
printf("The value of p is: %p\n", p);
printf("The direction of p is: %p\n", &p);
printf("The direction of s[0] is: %p\n", &s[0]);
printf("The direction of s[1] is: %p\n", &s[1]);
printf("The direction of s[2] is: %p\n", &s[2]);
return 0;
}
在用gcc编译它,我得到这些警告:
When compiling it with gcc I get these warnings:
$ gcc main.c -o main-bin -ansi -pedantic -Wall -lm
main.c: In function ‘main’:
main.c:6: warning: initialization from incompatible pointer type
main.c:9: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘char (*)[4]’
main.c:11: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘char **’
main.c:12: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘char ***’
(海合会的标志是,因为我必须C89)
(The flags for gcc are because I must be C89)
为什么不兼容类型的指针?不是一个数组的名字一个指向它的第一个元素?所以,如果s是一个指向'A',和放大器; s必须是一个char **,不是吗?
为什么我得到其他警告?我必须以打印出来投用(无效*)的指针?
Why incompatible types of pointer? Isn't the name of an array a pointer to it's first element? So if s is a pointer to 'a', &s must be a char **, no? And why do I get the other warnings? Do I have to cast the pointers with (void *) in order to print them?
和运行时,我得到的是这样的:
And when running I get something like this:
$ ./main-bin
The value of s is: 0xbfb7c860
The direction of s is: 0xbfb7c860
The value of p is: 0xbfb7c860
The direction of p is: 0xbfb7c85c
The direction of s[0] is: 0xbfb7c860
The direction of s[1] is: 0xbfb7c861
The direction of s[2] is: 0xbfb7c862
哪有S的值,它的方向(当然p值)是一样的吗?
How can the value of s and it's direction (and of course the value of p) be the same?
非常感谢你,
帕特里西奥
推荐答案
s是不是的char *,这是一个的char [4]。因此,与&amp; s不是一个焦炭**,但实际上是的指针4 characater的数组。你的编译器可能把&放大器; S为你写的。&放大器; S [0],这是大致相同的事情,不过是一个字符*
"s" is not a "char*", it's a "char[4]". And so, "&s" is not a "char**", but actually "a pointer to an array of 4 characater". Your compiler may treat "&s" as if you had written "&s[0]", which is roughly the same thing, but is a "char*".
当你写CHAR ** p =&S的;你是想说我想p来设置为的事情目前指向的地址ASD,但目前还没有哪个百分点的为ASD只是有一个数组其中的持有的ASD;
When you write "char** p = &s;" you are trying to say "I want p to be set to the address of the thing which currently points to "asd". But currently there is nothing which points to "asd". There is just an array which holds "asd";
char s[] = "asd";
char *p = &s[0]; // alternately you could use the shorthand char*p = s;
char **pp = &p;
这篇关于在C印花指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!