我需要用C语言帮助这个void函数。

时间:2011-06-13 18:13:49

标签: c

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

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

这是我做的无效功能。这个函数假设给我高度(h)和球击中地面的命中数(n)。这些数字由用户导入。

如果上述功能正确,我该怎么称呼它?

5 个答案:

答案 0 :(得分:6)

您可以按如下方式调用它:

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

&表示“取地址”。

但要小心:您的功能对错误的用户输入没有错误处理。

答案 1 :(得分:2)

您可以通过两种方式调用它:

// 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;

答案 2 :(得分:1)

insert(&h, &n)

& operator获取变量的地址(指向它的指针),然后将这些指针传递给函数。然后,Scanf将这些点用作写入用户输入值的位置。

答案 3 :(得分:0)

以下是您的代码应该是什么样的内容:

   #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一样,如果我输入一个3.5或任何不是int的东西,你的程序就会中断。

答案 4 :(得分:0)

这大多是正确的,但不保证显示printf()stdout可能是行缓冲的,因此您需要发出fflush()