Thread: Write to struct

  1. #1
    Registered User
    Join Date
    May 2011
    Posts
    68

    Write to struct

    I have a struct:
    Code:
    typedef struct command
    {
        char *name;  //command name
        char mode;   //0-read, 1- read/write 
        int minval;  
        int maxval;  
        void (*fp) (int com_num);  //pointer to function
        void *vp;   //pointer to variable
    }command;
    
    command commands[] = {
        {"imax1", 1, 0, 10000, GetSetImax, &max_current1},
        {"imax2", 1, 0, 10000, GetSetImax, &max_current2},
    };
    I can read from variable:
    Code:
    UsartSendInt( (int)commands[com_num].vp );
    But can not write to:
    Code:
    (int *)(commands[com_num].vp) =  10;
    What I'm doing wrong?

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Your second example is trying to set a pointer to have the value 10. Language rules don't generally allow setting pointers to have numeric values. That's why the compiler is forbidding the assignment.

    As to how to fix it ..... that depends on what you're really trying to achieve.

    I assume max_current1 and max_current2 are of type int, and you want your assignment to change those variables to have the value 10. In that case, you need to dereference the pointer on the left hand side of the assignment
    Code:
       *((int *)(commands[com_num].vp)) = 10;
    This will compile, but only have the intended effect if commands[com_num].vp points at an actual int. If commands[com_num].vp doesn't point at a valid int, the assignment will have undefined behaviour.


    Note that the first example is interpreting the value of a pointer as if it is an int. It is fairly unusual for that to have an intended effect - even though it does compile, since the (int) type conversion does bludgeon the compiler into submission.
    Last edited by grumpy; 07-14-2014 at 06:25 AM.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  3. #3
    Registered User
    Join Date
    May 2011
    Posts
    68
    Thank you very much.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Using binary write to save a struct
    By skan in forum C++ Programming
    Replies: 4
    Last Post: 08-14-2013, 06:57 AM
  2. Replies: 52
    Last Post: 05-11-2013, 03:17 PM
  3. struct holding data inside a linked list struct
    By icestorm in forum C Programming
    Replies: 2
    Last Post: 10-06-2009, 12:49 PM
  4. multiway read\write struct
    By quantt in forum C Programming
    Replies: 2
    Last Post: 02-02-2009, 10:13 AM
  5. problem with fout.write: cannot write 0x0A (10 dec)
    By yvesdefrenne in forum C++ Programming
    Replies: 7
    Last Post: 05-23-2005, 12:53 PM