简体   繁体   English

C程序中的指针

[英]Pointers in C-Program

I have a question about pointers in C. For example:我有一个关于 C 中指针的问题。例如:

int data[SIZE] = {2,4,5,1,0};
int *p = &data[2];
int **s=&p;
p++;
printf("%p  ", *s);

Is here the pointer *s equal to *p, ie is the adress of *s equal to *p?这里的指针*s 是否等于*p,即*s 的地址是否等于*p?

*It may be an easy question, but we didnt spend enough time learning C *这可能是一个简单的问题,但我们没有花足够的时间学习 C

After the declarations, you have the following:在声明之后,您有以下内容:

  s == &p                   // int ** == int **
 *s ==  p == &data[2]       // int *  == int *  == int *
**s == *p ==  data[2] == 5  // int    == int    == int    == int

After p++ :p++

 *s ==  p == &data[3]
**s == *p ==  data[3] == 1

If you run如果你跑

    int data[5] = {2,4,5,1,0};
    int *p = &data[2];
    int **s=&p;
    p++;
    int data[5] = {2,4,5,1,0};
    int *p = &data[2];
    int **s=&p;
    p++;
    printf("*p: %d  \n", *p);
    printf("&p: %p  \n", &p);
    
    printf("s: %p  \n", s);
    printf("*s: %p  \n", *s);
    printf("**s: %d  \n", **s);

you'll get:你会得到:

*p: 1  
&p: 0x7ffc69a74650  
s: 0x7ffc69a74650  
*s: 0x7ffc69a7466c  
**s: 1  

Which shows that the value pointed by both *p and **s is the same (1), also &p == s but &p and *s are not the same, as there's an extra "step".这表明*p**s指向的值是相同的 (1),也是&p == s&p*s不一样,因为有一个额外的“步骤”。

Here's a possible execution of your program:这是您程序的可能执行:

int data[SIZE] = {2,4,5,1,0};
// your memory looks like this:
// Address (name) -> Value
// 0x80 (data[0]) -> 2
// 0x84 (data[1]) -> 4
// 0x88 (data[2]) -> 5
// 0x8C (data[3]) -> 1
// 0x90 (data[4]) -> 0
int *p = &data[2];
// 0x80 (data[0]) -> 2
// 0x84 (data[1]) -> 4
// 0x88 (data[2]) -> 5
// 0x8C (data[3]) -> 1
// 0x90 (data[4]) -> 0
// 0xC0 (p)       -> 0x88
int **s=&p;
// 0x80 (data[0]) -> 2
// 0x84 (data[1]) -> 4
// 0x88 (data[2]) -> 5
// 0x8C (data[3]) -> 1
// 0x90 (data[4]) -> 0
// 0xC0 (p)       -> 0x88
// 0xD8 (s)       -> 0xC0
p++;
// 0x80 (data[0]) -> 2
// 0x84 (data[1]) -> 4
// 0x88 (data[2]) -> 5
// 0x8C (data[3]) -> 1
// 0x90 (data[4]) -> 0
// 0xC0 (p)       -> 0x8C
// 0xD8 (s)       -> 0xC0
printf("%p  ", *s); //Will print 0x8C

So no, *s (the value pointed by s) won't be equal to *p (the value pointed by p) but to p (the address of the p pointer)所以不,*s(s 指向的值)将不等于 *p(p 指向的值)而是等于 p(p 指针的地址)

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

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