2012-07-12 116 views
0

是什麼以下兩個任務之間的區別?鑄造指針和它的地址爲整型指針

int main() 
{ 
    int a=10; 
    int* p= &a; 

    int* q = (int*)p; <------------------------- 
    int* r = (int*)&p; <------------------------- 
} 

我對這兩個聲明的行爲非常困惑。
什麼時候應該使用一個比其他?

回答

10
int* q = (int*)p; 

是正確的,雖然過於冗長。 int* q = p就足夠了。 qp都是int指針。

int* r = (int*)&p; 

是不正確(從邏輯上講,儘管它可能編譯),因爲&pint**rint*。我想不出你想要這樣的情況。

0
int main() 
{ 
    int a=10; 
    int* p= &a; 

    int* q = p; /* q and p both point to a */ 
    int* r = (int*)&p; /* this is not correct: */ 
    int **r = &p; /* this is correct, r points to p, p points to a */ 

    *r = 0; /* now r still points to p, but p points to NULL, a is still 10 */ 
} 
2
#include <stdio.h> 
int main() 
{ 
    int a = 10; /* a has been initialized with value 10*/ 

    int * p = &a; /* a address has been given to variable p which is a integer type pointer 
        * which means, p will be pointing to the value on address of a*/ 

    int * q = p ; /*q is a pointer to an integer, q which is having the value contained by p,      * q--> p --> &a; these will be *(pointer) to value of a which is 10; 

    int * r = (int*) &p;/* this is correct because r keeping address of p, 
         * which means p value will be pointer by r but if u want 
         * to reference a, its not so correct. 
         * int ** r = &p; 
         * r-->(&p)--->*(&p)-->**(&p)        
         */ 
     return 0; 
} 
0

類型無所謂。

表達p具有類型int *(指針int),因此表達&p具有類型int **(指針的指針的int)。這些不同,不兼容類型;您無法將類型int **的值分配給int *類型的變量,而無需進行明確的轉換。

適當的事情是寫

int *q = p; 
int **r = &p; 

爲什麼您需要將值轉換爲不同的類型,你不應該使用有明確的轉換在分配中,除非你知道