2013-04-27 27 views
0

我試圖讓我的程序使用指針和malloc將Scanf的結果存儲到內存中,我希望Scanf只能接受interger,這裏是我的代碼。當我printf結果它回來了一個隨機數?指向帶有malloc的Scanf,不可預測的結果

int main(void) 
{ 

unsigned int *Source = malloc(10); 
printf("Enter a Source Number: "); 
scanf("%i",Source); 
printf("%i\n",Source); 
unsigned int *Destination = malloc(4); 
printf("Enter a Destination Number: "); 
scanf("%i",Destination); 
printf("%i\n",Destination); 
unsigned int *Type = malloc(4); 
printf("Enter a Type Number: "); 
scanf("%i",Type); 
printf("%i\n",Type); 
int *Port = malloc(4); 
printf("Enter a Port Number: "); 
scanf("%i",Port); 
printf("%i\n",Port); 
char *Data; 
struct Packet *next; 

return 0; 
} 

anoyone能解釋嗎?

回答

3
printf("%i\n",Source); 

是不確定的行爲,該%i轉換預期的int,但你傳遞一個int*。但可能它會嘗試打印指針值(地址)爲int。你打算使用

printf("%i\n", *Source); 

那裏。同樣的其他printf s。

傳遞給malloc的硬編碼值不是特別堅固的想法,更好malloc根據指針對象的大小,

unsigned int *Source = malloc(sizeof *Source); 
+0

哦,真不錯!謝謝,@undefined行爲。 – 2013-04-27 16:11:03

+0

*聳肩*。我們都出於同樣的原因在這裏... – Sebivor 2013-04-27 16:29:08

0
unsigned int *Source = malloc(10); 

源是一個指針。

printf("%i\n",Source); 

這段代碼打印值的地址,printf的這樣的值:

printf("%i\n",*Source);