C intro - How to pass a parameter by reference in function?

ⅰ亾dé卋堺 提交于 2021-02-10 05:35:51

问题


I'm working on my intro C course assignment and I'm tasked with the following...

  1. Write code for a function that receives two parameters (a,and b) by value and has two more parameters (c and d) by reference. All parameters are double.
  2. From main, use scanf to get two numbers, then call the function, and then display both returned values to the output in a printf statement.
  3. The function works by assigning (a/b) to c and assigning (a*b) to d.

While my knowledge is basic, I believe I understand the gists In main

      //first and second double hold the scanf inputs
      double first;
      double second;

      //unsure here - to reference c and d as parameters in the function, do I simply declare unfilled double variables here?
      double *c;
      double *d;

   printf("Enter your first number\n");
   scanf("%f\n", &first);
   printf("Enter your second number\n");
   scanf("%d\n", &second);

   //call the function, first and second by value, &c / &d by reference - correct?
   pointerIntro(first, second, &c, &d);

For the function...

float myFunction(double a, double b, double *c, double *d)
{
c = a/b;
d = a*b;


//printf statements
}

I apologize if the flow of this question is messy but its part of the process for me :P

So, for my formal questions 1. is it correct to initiate two double pointer variables (*c & *d) in main to be passed as reference in the function? 2. Am I right to call the function with the reference pointers by saying &c / &d? 3. Any other critiques of this questioning?


回答1:


  1. It is perfectly valid. You can initialize and pass any number of pointer variables with their reference.

  2. This is also valid..when you pass the variable address, you should store it into a pointers

you have to do some changes in your code, You can assign directly a/b and a*b pointer variables *c & *d Then you have to read double number with %lf format argument.

#include <stdio.h>
#include <string.h>

void myFunction(double a, double b, double *c, double *d)
{
*c = a/b;   //change
*d = a*b;   //change
printf("%lf %lf",*c,*d);
return;
//printf statements
}



int main()
{
//first and second double hold the scanf inputs
double first;
double second;

//unsure here - to reference c and d as parameters in the function, do I simply declare unfilled double variables here?
double *c;
double *d;

printf("Enter your first number\n");
scanf("%lf", &first);   //change
printf("Enter your second number\n");
scanf("%lf", &second);  //change

//call the function, first and second by value, &c / &d by reference - correct?
myFunction(first, second, &c,&d);
}



回答2:


Variables 'c' and 'd' don't have to be pointers to pass them by reference. So you have two cases:

  1. When you define 'c' and 'd' as pointers in main function you will pass them to function like this: pointerIntro(first, second, c, d); because they are already pointers and you don't need to send their reference, you just send them.

  2. If you define 'c' and 'd' just as double variables double c, d; you will send them to the function by reference using '&' symbol like this: pointerIntro(first, second, &c, &d);.

Then in your function to actually set the values of 'c' and 'd' you will need to dereference the pointer to them like this: *c = a/b; *d = a*b;.

If you are not familiar you can check what dereferencing the pointer means here: What does "dereferencing" a pointer mean?

Code that should work:

#include <stdio.h>

void myFunction(double a, double b, double *c, double *d)
{
    *c = a / b;
    *d = a * b;
}

int main(void)
{
    double a, b, c, d;

    scanf("%lf", &a);
    scanf("%lf", &b);

    myFunction(a, b, &c, &d);

    printf("%lf %lf", c, d);
}



回答3:


You need to dereference c and d to assign them in myFunction():

*c = a/b;
*d = a*b;

Moreover from main, you need to create instances to which c and d refer to:

double c;
double d;

(you had created unitialised pointers with no instances).

Then in the the call:

pointerIntro(first, second, &c, &d);

The & address-of operator creates the reference arguments, referring to c and d in main().

It might be useful not to use the same symbol names c and d in main() and myFunction() to make it clearer what they are. For example:

void myFunction(double a, double b, double* cptr, double* dptr )
{
    *cptr = a/b;
    *dptr = a*b;
}

Note also, a function that returns nothing should be declared void.




回答4:


A pointer is simply a normal variable that holds the address of something else as its value. In other words, a pointer points to the address where something else can be found. Where you normally think of a variable holding an immediate values, such as int a = 40;, a pointer (e.g. int *p = &a;) would simply hold the address where 40 is stored in memory.

If you need to access the value stored at the memory address pointed to by p, you dereference p using the unary '*' operator, e.g. int j = *p; will initialize j = 40).

If you want to obtain a variables address in memory, you use the unary '&' (address of) operator. If you need to pass a variable as a pointer, you simply provide the address of the variable as a parameter.

In your case that boils down to writing your function similar to:

void multdiv (double a, double b, double *c, double *d)
{
    *c = a / b;
    *d = a * b;
}

(note: you should ensure b != 0 before dividing a / b -- that is left to you)

In order to provide storage for the values you will take as input as well as the values you want to hold the results of the multiplication and division, you need four double values, e.g.

int main (void) {

    double a, b, c, d;          /* your doubles */

You then need to prompt the user for input and validate the user input by checking the return of the input function used, e.g.

    fputs ("enter two double values: ", stdout);        /* prompt */
    fflush (stdout);    /* flush stream (optional but recommended) */

    if (scanf ("%lf %lf", &a, &b) != 2) {   /* validate EVERY input */
        fputs ("error: invalid double values.\n", stderr);
        return 1;
    }

(bonus: Why is the '&' used before a and b with scanf above? See first full paragraph under DESCRIPTION in man 3 scanf)

All that remains is to call your function to perform the calculations and output the results, e.g.:

    multdiv (a, b, &c, &d);     /* calculate c, d */

    printf ("\nc = a / b  => %.2f\nd = a * b  => %.2f\n", c, d);

(note: as explained above the address of operator is used to pass the address of c and d as parameters)

Putting it altogether you could do:

#include <stdio.h>

void multdiv (double a, double b, double *c, double *d)
{
    *c = a / b;
    *d = a * b;
}

int main (void) {

    double a, b, c, d;          /* your doubles */

    fputs ("enter two double values: ", stdout);        /* prompt */
    fflush (stdout);    /* flush stream (optional but recommended) */

    if (scanf ("%lf %lf", &a, &b) != 2) {   /* validate EVERY input */
        fputs ("error: invalid double values.\n", stderr);
        return 1;
    }

    multdiv (a, b, &c, &d);     /* calculate c, d */

    printf ("\nc = a / b  => %.2f\nd = a * b  => %.2f\n", c, d);

    return 0;
}

Example Use/Output

$ ./bin/multdivbyptrs
enter two double values: 4.0 2.0

c = a / b  => 2.00
d = a * b  => 8.00

Look things over and let me know if you have questions. Once you digest that a pointer is simply a normal variable that holds the address where something else is stored as its value -- things will start to fall into place. No magic..




回答5:


Here is the correct way to do it. The func() method

void func(double x,double y,double *z,double *w){
    printf("pass by value = %lf, %lf",x,y);
    printf("pass by reference = %lf, %lf",*z,*w);
}

The main() method

int main(void){
   double first,second,val1,val2;
   val1=3.1;
   val2=6.3;
   printf("Enter your first number\n");
   scanf("%lf", &first);
   printf("Enter your second number\n");
   scanf("%lf", &second);
   func(first,second,&val1,&val2);  
}


来源:https://stackoverflow.com/questions/58888981/c-intro-how-to-pass-a-parameter-by-reference-in-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!