Search code examples
cmicrocontrolleravr

Structure value is not updating in main source file


part of my project some of source files are button_key.h, button_key.h, lcd.h, mani.c etc.

Used a structre in button_key.H and declared as

struct menu {
             uint8_t Hour;
             uint8_t Minute;
             uint8_t Second;
            };

In main.c source file

#include "lcd.h"
#include "delay.h"
#include "button_key.h"

  struct menu s1= {0}; 
  struct menu *ptr; 

int main(void)
{   int a;

    ptr = &s1;

//some code//
menu_key_display (s1,menu_display);
LCD_DisplayNumber(10,(*ptr).Hour,2); // here not updating the structure value as per the code in button_key.c  only show zero (0)
  while(1);

  // tried also LCD_DisplayNumber(10,s1.Hour,2); also seems same reult.

}

And the structre is used in button_key.c file like (only the part of the code)

 void menu_key_display(struct menu s1,const char *menu_display[])
 {   //some cdoe here
       case 1: // set time
             { 
             LCD_Clear();
             LCD_GoToLine(0);
             LCD_DisplayString(menu_display[5]);
             LCD_GoToLine(1);
             LCD_DisplayString("  HH:MM:SS:PM/AM");
             UP_Down_Keyvalue(s1,2,4);            
              break;

             // some code 
 }

The above source code made changes , the values to the menu structure members. But that changes not reflect in main.c whats the wrong with me.


Solution

  • Compiling an answer from comments:

    The lack of updating is only visible in the lines you commented in your code, i.e. they are only the symptom.

    The cause of the problem is one line earlier:

    menu_key_display (s1,menu_display);
    //                ^
    

    In order to get the changes inside the function visible outside,
    you need to use "call by reference", which in C means "via a pointer".

    So, change the offending line to:

    menu_key_display (ptr,menu_display);
    

    That of course has to be matched by changes to lines of the called function:

    void menu_key_display(struct menu *s1Ptr, const char *menu_display[])
    // ...
    UP_Down_Keyvalue(s1Ptr,2,4); // assuming this to be supposed to have the missing effect
    //                ^
    

    The last use of the pointer (in contrast to "call by value" struct copy) needs to be reflected in the UP_DownKeyvalue(...) function, too, in a similar way. However, if it is a macro (which I think I implicitly assumed in the previous version of my answer), then UP_Down_Keyvalue(*s1Ptr,2,4); could be used without change to the macro definition.

    Note, when working with pointer you might want to add a check to the function, to make sure that the pointer is not NULL. Call it paranoia, but paranoia is a healthy state of mind for a programmer (at least an embedded programmer).