2015-05-11 178 views
1

我試圖通過爲自己闡明指針指向的地址,指針本身的地址和地址引用的值來理解簡單指針。所以我寫了一小段代碼:(請不要糾正我,如果我在這裏犯任何錯誤)聲明指向指向指針的指針

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
    int a; 
    int *p; 
    int **pp; 

    a = 42; 

    /* Take the address of a */ 
    p = &a; 

    /* Take the address of p */ 
    pp = &p; 

    printf("Address of int &a:       %p\n\n", &a); 
    printf("value of a:         %d\n\n", a); 

    printf("Address where *p points to via (void *)p: %p\n\n", (void *)p); 
    printf("Value that *p points to via *p:    %d\n\n", *p); 
    printf("Address of *p itself via (void *)&p:  %p\n\n", (void *)&p); 

    printf("Address where **p points to via (void *)pp: %p\n\n", (void *)pp); 
    printf("Value that **pp points to via **pp:   %d\n\n", **pp); 
    printf("Address of **p itself via (void *)&pp:  %p\n\n", (void *)&pp); 
    return EXIT_SUCCESS; 
} 

這如預期的所有作品。現在,我想深入一層,並使用指向指針***ppp的指針的指針,併爲其指定地址,指向指針pp的指針指向的地址爲*p指向的地址爲a。這是我以爲我可以做到這一點:

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
    int a; 
    int *p; 
    int **pp; 
    int **ppp; 

    a = 42; 

    /* Take the address of a */ 
    p = &a; 

    /* Take the address of p */ 
    pp = &p; 

    ppp = &pp; 

    printf("Address of int &a:        %p\n\n", &a); 
    printf("value of a:          %d\n\n", a); 

    printf("Address where *p points to via (void *)p:  %p\n\n", (void *)p); 
    printf("Value that *p points to via *p:     %d\n\n", *p); 
    printf("Address of *p itself via (void *)&p:    %p\n\n", (void *)&p); 

    printf("Address where **pp points to via (void *)pp:  %p\n\n", (void *)pp); 
    printf("Value that **pp points to via **pp:    %d\n\n", **pp); 
    printf("Address of **pp itself via (void *)&pp:   %p\n\n", (void *)&pp); 

    printf("Address where ***ppp points to via (void *)ppp: %p\n\n", (void *)ppp); 
    printf("Value that ***ppp points to via ***ppp:   %d\n\n", ***ppp); 
    printf("Address where ***ppp points to via (void *)&ppp: %p\n\n", (void *)&ppp); 

    return EXIT_SUCCESS; 
} 

但是,這給了我一個不兼容的指針警告。有人可以向我解釋爲什麼這不起作用,如果撥打printf()是正確的?

+1

你得到的確切警告是什麼,它是什麼線? – interjay

+3

'int ** ppp;'應該是'int *** ppp;'。另外,'(void **)* ppp'不正確。它應該是'(void *)* ppp'。 –

+0

Da ** it。我應該留下以備日後參考或刪除問題嗎? –

回答

2

的問題是在這裏:

int **ppp; 

這應該是

​​

因爲它是現在你試圖迫使三指針,爲雙指針。這將可能讓你在這條線的錯誤:

ppp = &pp; 

此外你可能想看看this article :)的2號。

P.s. 如果您提供行號和特定錯誤,以備將來參考。人們可能想幫助你甚至更好:)

3

錯誤在這一行 int ** ppp;/*它應該是*** ppp,因爲你指向一個指向另一個的指針*/