整數

2014-03-31 20 views
0

我的任務使用scanf函數是創建數組,爲了做到這一點,我需要投入的大小,但我必須確保輸入是不是負數,字母或符號。我創建了這個功能,但我的if不能正常工作。如果我輸入負數或字符,它仍然使用它。整數

下面是我使用的功能:

void getsize(int* size){ 
    printf("Enter the size of array\n"); 
    if ((scanf("%d", size) == 1) && (getchar() == '\n') && (size > 0)){ 
    printf("Size: %d entered\n", *size); 
    } else { 
    printf("wrong input\n"); 
    while(getchar() != '\n'); 
    } 
} 

getsize(&size); 
+0

'「%d」'不會反正得到非數字字符... – ThoAppelsin

回答

3

的主要問題是,你的價值的地址與0 size是一個指針,所以用:

(*size > 0) 

代替

(size > 0) 
2

您的指針與0比較,而不是TH您存儲在指向的內存位置的e值。在你的if語句

... (*size > 0)) { ... } 
1

:裏面你if,而使用以下內容作爲最後的比較。你檢查size > 0 這應該是*size > 0

0
void getsize(int* size){ 
    printf("Enter the size of array\n"); 
    if ((scanf_s("%d", size) == 1) && (getchar() == '\n') && (*size > 0)){ 
     printf("Size: %d entered\n", *size); 
    } 
    else { 
     printf("wrong input\n"); 
     while (getchar() != '\n'); 
    } 
} 

這對我的作品。只需將大小> 0更改爲*大小> 0,因爲您必須檢查該值,而不是地址。