簡體   English   中英

我需要 C 語言中的這個 void function 的幫助。?

[英]I need help with this void function in C language.?

void insert(int* h, int* n)
{
    printf("give numbers");

    scanf("%d %d", h, n);
}

這是我制作的 void function。 這個 function 應該給我高度(h)和球擊中地面的次數(n)。 這些號碼由用戶導入。

如果上面的 function 是正確的,我該怎么稱呼它?

你可以這樣稱呼它:

int h;
int n;
insert(&h, &n);

其中&表示“獲取地址”。

但要小心:您的 function 對錯誤的用戶輸入沒有錯誤處理。

您可以通過兩種方式調用它:

// Method 1
int h, n;
insert(&h, &n);

// Method 2 (if you need to return the pointers or anything else weird for some reason
// I think this is useful in some cases when you are using a library that requires you
// to pass in heap-allocated memory
int *h = malloc(sizeof(int));
int *n = malloc(sizeof(int));
if(h == NULL || n == NULL)
     exit(1);

insert(h, n);

// Stuff

free(h);
free(n);
h = n = NULL;
insert(&h, &n)

& 運算符獲取變量的地址(指向它的指針),然后將這些指針傳遞給 function。 Scanf 然后使用這些點作為寫入用戶輸入值的位置。

這是您的代碼應該是什么樣子:

   #include <stdio.h>

   void insert(int*, int*)

   int main()
   {
      int n, h;
      insert(&h, &n);

      return 0;
   }
   void insert(int* h, int* n)
   {
       printf("give numbers");

       scanf("%d %d", h, n);
   }

但是,就像@Oli 一樣,如果我輸入 a、3.5 或任何不是 int 的值,您的程序就會中斷。

它大部分是正確的,但不保證會顯示printf() stdout可能是行緩沖的,因此您需要發出fflush()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM