2011-09-09 130 views
1
int main() 
{ 
double x = 10.08; 
double *p; 
p = &x; 
printf("value of pointer is %d\n",p); 
*p=&x;//error line 
printf("value of x, *p = %lf\n",x); 
return 0; 
} 

當我這樣做的int類型(即int x,int * p),它的工作正常。但不是雙重的,爲什麼?指針不兼容類型錯誤

+0

我是一個總C newb。這就是說,你遇到了問題,因爲在'* p =&x'中,你正在引用'p'並將它分配給一個指向'x'的指針。我不相信這與'int'和'double'有什麼關係 – 2011-09-09 05:44:55

+1

你認爲那行代碼要做什麼? (提示:你可能是錯的,反思指針,聲明一個指針和使用一元'*'運算符的區別) –

+0

你的意思是* p = x;在錯誤線上?你是否試圖將x的值存儲到p指向的地址? (void *)p);' –

回答

2

*p有型號double; &x有型號double *。它們不兼容。

順便提及,打印出的指針值,使用轉換%p

printf("value of pointer is %p\n", p); 
0

*p的類型爲double。 &x是指向雙精度型的類型。你爲什麼期望它們兼容?

我希望你的編譯器,如果你打開(並閱讀)的警告,抱怨,即使與int s。

+0

int main int * p; p =&x; printf(「指針的值是%d \ n」,p); * p =&x; printf(「x的值,* p =%d \ n」,x); return 0; } 只是運行它,它的工作正常。 – Gopal

+1

**打開編譯器**的警告。 'tc:在函數'main'中: tc:7:2:warning:格式'%d'期望類型'int',但參數2的類型爲'int *' tc:8:4:warning:賦值使整數從沒有投的指針 ' – Mat

-1

更換

*p = &x       with  *p = (unsigned int) &x \\ this works 
*p = &x it means x = &x ; Not a syntax to follow 

雖然這不是因爲* P,它inturns應遵循c表示x值,你想保存在x值的地址,但你沒有聲明爲指針,但只是一個正常的變量。

但是與詮釋你沒有得到任何錯誤,但表明

non portable assigment 

我不知道根基深厚,但對於我的調查,我猜指針保存的地址在其他一些格式,但顯示警告我們的整數格式

int x; 
int *p; 
p = &x ; 
*p = &x ; warning non portable assignment replace with *p = (unsigned int) &x 

using typecasting (unsigned int) coverts the address format to integer format 
I guess So . May be the address format and integer format are different 
Thats why you cant assign address to a variable unless it is typecasted 
but pointers dont need them because as they are invented to store the address 
This is what i think from my investigation 

但我強烈建議不要遵循上面的語法。

人們不總是使用雙指針而是去虛空指針

+0

爲什麼我得到-1 MR downvoter – niko