Thread: Pointers and Call-by-reference functions

  1. #1
    Registered User
    Join Date
    Nov 2017
    Posts
    29

    Pointers and Call-by-reference functions

    I'm kicking off on another semester in C programming and one thing I have not been able to successfully wrap my head around is pointers, and then their employment in call-by-reference functions. Can anyone walk me through the concept and application of these? Really I need a basic working example that can then be referenced for the first assignment described below.

    The first assignment takes in five values in the main and passes them to functions to do the following: "The task is to create second-degree polynomial calculator for the function, its integral and its derivative."

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,907
    I'm not really clear what the assignment is asking and where pass by reference fits into that. Regardless, here's a summary of how it works:

    Everything in C is, in a sense, pass-by-value. Take the following:
    Code:
    #include <stdio.h>
    
    void do_stuff(int x) {
        printf("In do_stuff, before increment x = %d\n", x);
        x += 1;
        printf("In do_stuff, after increment x = %d\n", x);
    }
    
    int main(void) {
        int x = 42;
        printf("In main, before do_stuff x = %d\n", x);
        do_stuff(x);
        printf("In main, after do_stuff x = %d\n", x);
    }
    If you compile and run that, you get the following:
    Code:
    In main, before do_stuff x = 42
    In do_stuff, before increment x = 42
    In do_stuff, after increment x = 43
    In main, after do_stuff x = 42
    When you pass x from main to do_stuff, you are passing by value. In otherwords, a copy of the value of x (42) is passed into do_stuff (as parameter x). So x in do_stuff is a different x than the one in main. When it's incremented on line 5, you are incrementing the value of the copy of x in do_stuff. The one in main is not touched.

    So how do we write a function that changes the value of whatever is passed in in such a way that the change is reflected in the calling function? With pointers.

    A pointer stores the address of an object. You can think of it like an entry in an address book. You have the address of your friend's house. You know where to find it, but you don't have the house itself.

    So when you want to change the value of a variable, you give the function a pointer to (the address of) that variable. That tells the function where to find the original variable, so it can modify it. Let's rewrite our example above to use pointers so do_stuff can modify x:

    Code:
    #include <stdio.h>
    
    void do_stuff(int *x) {
        printf("In do_stuff, *x = %d\n", *x);
        *x += 1;
        printf("In do_stuff, *x = %d\n", *x);
    }
    
    int main(void) {
        int x = 42;
        printf("In main, x = %d\n", x);
        do_stuff(&x);
        printf("In main, x = %d\n", x);
    }
    When you run that, you get the following. Note that x in main has been changed.
    Code:
    In main, before do_stuff x = 42
    In do_stuff, before increment *x = 42
    In do_stuff, after increment *x = 43
    In main, after do_stuff x = 43
    What's with all the * and & in the code? I've broken them down into 3 groups, by color:

    • This declares x as a pointer to an int (not as an actual int). That allows do_stuff to take the address of an int so it can modify that int.
    • This is how you get the value stored. Because we have a pointer to (address of) an int, we can't add to the number directly. We have to dereference (get to) the actual int to see it's value or modify it. That's what putting a * before x in the body of the function does.
    • This gets the address of x. We no longer pass in a copy of the value of x, we pass in a copy of the address of x.
    Last edited by anduril462; 01-08-2018 at 09:28 PM. Reason: Color and wording fixes

  3. #3
    Registered User
    Join Date
    Nov 2017
    Posts
    29
    Below is the instructions for the program to be written. The steps that specify call by reference with pointers are 4 and 7; it copied in funny. I'm suspecting there is going to be some sort of for loop and MD arrays for storing and then printing the results of the tested range. These I have also struggled to understand so I'm willing to take this piece by piece.



    1. First,read this document in its entirety. After reading this handout, you may optionallycreate a design sheet for the problem. Your design sheet should help youdetermine what header files, functions and variables you will need as well asidentifying expected test results. You do NOT turn in your designsheet.

    2. Whenyou write your code, include the usual (detailed) comment block includingprogram name, author, date, inputs, outputs and description.

    3. Createa function of type void to explain the program to theuser with the description printed to the terminal. Do not forget to callthe function from main().

    4. Inputthe data while executing from your main()function. Query the user to enter the data. You must enter theparameters from the user in the following order: a, b, c and then https://cboard.cprogramming.com/imag...mDR1Q1ikhfCAA7, https://cboard.cprogramming.com/imag...GMJeaJVIUAADs= and https://cboard.cprogramming.com/imag...wgBI6AlygEADs=. Use doublefor all variables and calculations.




    1. Yourprogram is to loop over all possible x values in your main() function. The first x value is to be https://cboard.cprogramming.com/imag...mDR1Q1ikhfCAA7, the second https://cboard.cprogramming.com/imag...SVliSClykhADs=, etc. with the last value being https://cboard.cprogramming.com/imag...GMJeaJVIUAADs= (or somewhat less thanhttps://cboard.cprogramming.com/imag...GMJeaJVIUAADs= if https://cboard.cprogramming.com/imag...wgBI6AlygEADs= does not divide evenlyinto the range).

    2. Thecalculation of the area A depends on the initial value of x, https://cboard.cprogramming.com/imag...mDR1Q1ikhfCAA7. That is, for each x, we calculate the area as https://cboard.cprogramming.com/imag...XrsADjAAQBADs=. In order to calculate A, you must know both xand https://cboard.cprogramming.com/imag...mDR1Q1ikhfCAA7. For the first value of x, it should be that A is zero.

    3. Frommain() and for each x,you are to call a call-by-referencefunction that accepts a, b, c, xand https://cboard.cprogramming.com/imag...mDR1Q1ikhfCAA7 that calculates andreturns (via pointer operations) https://cboard.cprogramming.com/imag...E4Cw9SYo9FIQA7, https://cboard.cprogramming.com/imag...JShUM7MCIhADs= and A. That is,you must create a single function that accepts five input parameters (a, b,c, x and https://cboard.cprogramming.com/imag...mDR1Q1ikhfCAA7), and returns three outputs (related to https://cboard.cprogramming.com/imag...E4Cw9SYo9FIQA7, https://cboard.cprogramming.com/imag...JShUM7MCIhADs= and A). There must not be any scan/print statementsin your function.

    4. Yourfunction uses the values of a, b and c along with the value of xto compute https://cboard.cprogramming.com/imag...qt4mmu3btBAAA7. Similarly, the derivative is computed as https://cboard.cprogramming.com/imag...RcsvSo0ylBAAA7. Then, using https://cboard.cprogramming.com/imag...mDR1Q1ikhfCAA7 in addition to theother parameters, compute https://cboard.cprogramming.com/imag...57mYm8gwAAOw== and https://cboard.cprogramming.com/imag...lhlNoqujkIADs=. The area is found as https://cboard.cprogramming.com/imag...WrV6Kk0AkJAgA7. Return the result of your calculations back to the main() function (it will be necessaryto reference your outputs via pointers).

    5. Alloutput for your table of x versus https://cboard.cprogramming.com/imag...E4Cw9SYo9FIQA7, https://cboard.cprogramming.com/imag...JShUM7MCIhADs= and A must be displayedvia statements in your main()function. Write your table to the terminal (i.e., the default output for printf()).Choose a suitable format for your output numbers.


  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,926
    scotdani, I cannot fathom why this is so, but it looks like your post #3 has been mangled with the insertion of links.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User
    Join Date
    Nov 2017
    Posts
    29
    Quote Originally Posted by laserlight View Post
    scotdani, I cannot fathom why this is so, but it looks like your post #3 has been mangled with the insertion of links.
    I think it's because the doc used Equation Editor and didn't translate well when I copied it. I'll repost shortly.

  6. #6
    Registered User
    Join Date
    Nov 2017
    Posts
    29
    Hopefully this works:

    1. First,read this document in its entirety. After reading this handout, you may optionallycreate a design sheet for the problem. Your design sheet should help youdetermine what header files, functions and variables you will need as well asidentifying expected test results. You do NOT turn in your designsheet.

    2. Whenyou write your code, include the usual (detailed) comment block includingprogram name, author, date, inputs, outputs and description.

    3.Createa function of type void to explain the program to theuser with the description printed to the terminal. Do not forget to callthe function from main().

    4, Inputthe data while executing from your main()function. Query the user to enter the data. You must enter theparameters from the user in the following order: a, b, c and then x(I), x(f), and deltaX. Use doublefor all variables and calculations.

    5. Yourprogram is to loop over all possible x values in your main() function. The first x value is to be x(I) the second x(I) + deltaX, etc. with the last value being x(f) (or somewhat less than x(f), if deltaX does not divide evenlyinto the range).

    6. Thecalculation of the area A depends on the initial value of x, x(I). That is, for each x, we calculate the area as A = F(x) - F(x(I)). In order to calculate A, you must know both xand x(i). For the first value of x, it should be that A is zero.

    7. Frommain() and for each x,you are to call a call-by-referencefunction that accepts a, b, c, xand x(I) that calculates andreturns (via pointer operations) f(x), f'(x) and A. That is,you must create a single function that accepts five input parameters (a, b,c, x and x(I)), and returns three outputs (related to f(x), f'(x) and A). There must not be any scan/print statementsin your function.

    8.Yourfunction uses the values of a, b and c along with the value of xto compute f(x) = ax^2 + bx +c. Similarly, the derivative is computed as f'(x) = 2ax + b. Then, using x(I) in addition to theother parameters, compute F(x(I)) = (a/3)x(I)^3 + (b/x2)x(I)^2 + cx(I) and F(x) =(a/3)x^3 + (b/2)x^2 + cx. The area is found as A = F(x) - F(x(I). Return the result of your calculations back to the main() function (it will be necessaryto reference your outputs via pointers).

    9Alloutput for your table of x versus f(x), f'(x) and A must be displayedvia statements in your main()function. Write your table to the terminal (i.e., the default output for printf()).Choose a suitable format for your output numbers.


  7. #7
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,907
    Can you post what code you have so far? You should be able to handle several of the requirements without using pointers or pass-by-reference. It would be good to see your attempt at the pass-by-reference stuff as well, it will help us see where your misunderstandings are and better help you.

  8. #8
    Registered User
    Join Date
    Nov 2017
    Posts
    29
    Quote Originally Posted by anduril462 View Post
    Can you post what code you have so far? You should be able to handle several of the requirements without using pointers or pass-by-reference. It would be good to see your attempt at the pass-by-reference stuff as well, it will help us see where your misunderstandings are and better help you.
    I do not have much going on yet since I have four weeks to finish it up. In general I don't know how to use pointers but even the prof said the purpose is to get us using these more regularly since we are building a robot and have it working by midterm.

  9. #9
    Registered User
    Join Date
    May 2009
    Posts
    3,880
    I would start out by doing the function prototypes.
    Then, start working on the functions you understand how to do.

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  10. #10
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,907
    Forums are not the best place for lecture-level teaching. They better serve specific questions and help with specific issues. Also, if your prof is giving 4 weeks for this assignment, they may have more lectures and practice work on pointers to help you out.

    That being said, I'm happy to help where I can. For starters, here are couple online references that seem decent (I only took a cursory look at them):
    Keeping it Simple: C Pointers Explained, Really
    C Tutorial – How to use Pointers | CodingUnit Programming Tutorials

    There's lots more out there. There's also one particular video I'm thinking of, but can't find at the moment.

    There's no replacement for actually trying/doing this yourself. Even if the road is bumpy. Best thing about programming though, is that you can try all this out yourself easily. The cost of failure is basically zero. Worst case scenario, your program crashes or inifinite-loops. Tweak it and try again. No real harm done.

  11. #11
    Registered User
    Join Date
    Nov 2017
    Posts
    29
    Quote Originally Posted by anduril462 View Post
    Forums are not the best place for lecture-level teaching. They better serve specific questions and help with specific issues. Also, if your prof is giving 4 weeks for this assignment, they may have more lectures and practice work on pointers to help you out.

    That being said, I'm happy to help where I can. For starters, here are couple online references that seem decent (I only took a cursory look at them):
    Keeping it Simple: C Pointers Explained, Really
    C Tutorial How to use Pointers | CodingUnit Programming Tutorials

    There's lots more out there. There's also one particular video I'm thinking of, but can't find at the moment.

    There's no replacement for actually trying/doing this yourself. Even if the road is bumpy. Best thing about programming though, is that you can try all this out yourself easily. The cost of failure is basically zero. Worst case scenario, your program crashes or infinite-loops. Tweak it and try again. No real harm done.
    Thanks for the resources. I will keep these in mind. Programming is definitely something that is still quite foreign to me but I definitely have gained appreciation for those that excel at it.

    Here is what I have started so far. My understanding of custom functions is very little and what I did learn in the fall is hazy.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    
    void program_intro;
    int main()
    {
        program_intro;
        return 0;
    }
    void program_intro; //Explanation of this program for user
        {
            printf("This program will compute a range of values for\n");
            ("the second degree polynomial f(x) = ax^2 + bx + c it's\n");
            ("derivative f'(x) = 2ax + b, it's integral\n");
            ("F(x[i])=(a/3)x[i]^3 + (b/2)x[i]^2 + cx, and the\n");
            ("area A = F(x) - F(x[i]).\n\n")
            return void;
        }

  12. #12
    Registered User
    Join Date
    May 2009
    Posts
    3,880
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  13. #13
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,907
    Yeah, check out the link stahta01 provided.

    A few notes:

    • No semicolon at the end of the function definition (line 11).
    • You do need parentheses at the end of a funciton definition.
    • Any parameters would go inside those parentheses. If there are no parameters for a function, I recommend putting the word void inside the parens to be explicit.
    • You need a printf for each line of output in program_intro.
    • You don't return void; A function that "returns" void actually returns nothing, so there's usually no need for a return statement1. If you do want one, it's just return; no void.


    1Sometimes you use one to return from a function early (somewhere other than the last line of the function).

  14. #14
    Registered User
    Join Date
    Nov 2017
    Posts
    29
    I made some progress in writing out the beginning of this program. I think this is where I need to start working on using pointer language. If I understand you're first response, I need a second declaration of my variables, i.e. *a, *b etc, to pass them back and forth between main and other functions. I'm just testing right now to do a scan in a function then print it out in main.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    void program_intro(void);
    float input_read(float a, float b, float c, float x_initial, float x_final, float x_delta);
    int main()
    {
        float a, b, c, x_initial, x_final, x_delta;
        program_intro();
        input_read(a, b, c, x_initial, x_final, x_delta);
        printf("a = %2.f\n", a);
        printf("b = %2.f\n", b);
        printf("c = %2.f\n", c);
        printf("x = %2.f\n", x_initial);
        printf("x[i] = %2.f\n", x_final);
        printf("delta X = %2.f\n", x_delta);
        return 0;
    }
    void program_intro(void) //Explanation of program to the user
        {
            printf("This program will compute a range of values for\n");
            printf("the second degree polynomial f(x) = ax^2 + bx + c,\n");
            printf("the derivative f'(x) = 2ax + b, \n");
            printf("the integral F(x[i]) = (a/3)x[i]^3 + (b/2)x[i]^2 + cx, and the\n");
            printf("area A = F(x) - F(x[i]).\n\n");
            return;
        }
    float input_read(float a, float b, float c, float x_initial, float x_final, float x_delta)
        {
            printf("Please input the polynomial coefficients as follows:\n\n");
            printf("Coefficient a: ");
            scanf("%f", &a);
            printf("\nCoefficient b: ");
            scanf("%f", &b);
            printf("\nCoefficient c: ");
            scanf("%f", &c);
            printf("\n\nPlease input the range and increment to be tested as follows:\n\n");
            printf("x: ");
            scanf("%f", &x_initial);
            printf("\nx[i]: ");
            scanf("%f", &x_final);
            printf("\ndelta x: ");
            scanf("%f", &x_delta);
        return a, b, c, x_initial, x_final, x_delta;
        }

  15. #15
    Registered User
    Join Date
    May 2009
    Posts
    3,880
    In C, you can only return at most a single variable value.

    Therefore this line will not work.
    Code:
    return a, b, c, x_initial, x_final, x_delta;
    This can be fixed by using pointers.

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 11-11-2013, 06:53 PM
  2. functions and pointers (call by value)
    By bos1234 in forum C Programming
    Replies: 3
    Last Post: 02-14-2011, 06:49 AM
  3. Sending array's to functions by reference or pointers
    By homeyg in forum C++ Programming
    Replies: 16
    Last Post: 12-27-2004, 02:55 PM
  4. Call-by-value Vs. Call-by-reference
    By Wiz_Nil in forum C++ Programming
    Replies: 3
    Last Post: 02-20-2002, 09:06 AM
  5. call by reference and a call by value
    By IceCold in forum C Programming
    Replies: 4
    Last Post: 09-08-2001, 05:06 PM

Tags for this Thread