开发者

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

开发者 https://www.devze.com 2023-03-12 08:56 出处:网络
void insert(int* h, int* n) { printf(\"give numbers\"); scanf(\"%d %d\", h, n); } This is the void function I made. This function is suppose to give me the height(h) and the numbe开发者_StackOverfl
void insert(int* h, int* n)
{
    printf("give numbers");

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

This is the void function I made. This function is suppose to give me the height(h) and the numbe开发者_StackOverflowr of hits(n) the ball hits the ground. These numbers are imported by a user.

If the function above is correct, how do I call it?


You can call it as follows:

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

Where the & means "take the address of".

But be careful: Your function has NO error-handling for erroneous user-input.


You can call it in two ways:

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

The & operator gets the address of the variables (a pointer to it), and then passes those pointers to the function. Scanf then uses those points as places to write the values the user enters.


It's mostly correct, but that printf() isn't guaranteed to be shown. stdout may be line buffered, so you would need to issue a fflush().


Here is what your what your code should look like:

   #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);
   }

However like @Oli your program would break if I input a, 3.5, or anything not an int.

0

精彩评论

暂无评论...
验证码 换一张
取 消