Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Problem with pointer and structures in C

  1. Jan 22, 2012 #1
    I'm trying to point to the data in struct ele709_record john_doe into the total_mark function. But it's not working, the value returned is not the same as in struct.

    #include <stdio.h>

    struct lab {

    double experiment1;
    double experiment2;
    double experiment3;
    };

    struct theory{
    double test;
    double final;
    };

    struct ele709_record{
    struct lab lab_mark;
    struct theory theory_mark;
    };

    double total_mark(struct ele709_record *p)
    {
    double totalmark;
    p->lab_mark.experiment1 = totalmark;
    return totalmark;


    }

    int main()
    {

    double john_doe_mark;

    struct ele709_record john_doe;


    john_doe.lab_mark.experiment1= 90.2;
    john_doe.lab_mark.experiment2= 70.5;
    john_doe.lab_mark.experiment3= 80.4;
    john_doe.theory_mark.test= 82.3;
    john_doe.theory_mark.final=79.2;

    john_doe_mark = total_mark(&john_doe);

    printf("this is his mark %lf\n",john_doe_mark);

    }
     
  2. jcsd
  3. Jan 22, 2012 #2
    In your function total_mark what is double totalmark suppose to be? Your not initializing it, in other words you are returning a random number in memory.
     
    Last edited: Jan 22, 2012
  4. Jan 22, 2012 #3
    the function total_mark will be used later to calculate the total mark based on weight percentages of the labs,test and final exam. For now i just want to see if i can point to a member in my structure to the function and then return it
     
  5. Jan 22, 2012 #4
    So what is it returning and what do you want it to return what exact numbers? Right now you are returning an un assigned variable and you are getting random number in memory.
     
  6. Jan 22, 2012 #5

    DrGreg

    User Avatar
    Science Advisor
    Gold Member

    Er, did you really intend to write
    Code (Text):
    totalmark = p->lab_mark.experiment1;
    instead of
    Code (Text):
    p->lab_mark.experiment1 = totalmark;
    ?
     
  7. Jan 22, 2012 #6

    Mark44

    Staff: Mentor

    When you post code, please surround it with a [noparse]
    Code (Text):
     tag at the top and a
    [/noparse] tag at the bottom. This preserves your indentation and makes you code easier to read and understand.
    I have done this for your code.
    Change your function as follows:

    Code (Text):

    double total_mark(struct ele709_record  *p)
    {
       double totalmark = p -> lab_mark.experiment1;
       // p->lab_mark.experiment1 = totalmark;
       return totalmark;
    }
     
     
  8. Jan 22, 2012 #7
    Sorry about that.

    THANKS SO MUCH!!!
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Problem with pointer and structures in C
Loading...