Why struct not globally changed in function?

Joined
Jul 16, 2023
Messages
8
Reaction score
3
In the proof of concept code below, I pass a button structure to a function. Inside the function a strcut value is changed but the change only occurs locally. The attempt to set a new struct value is in the 3rd line from the bottom.

1) I thought struct definitions were passed by reference not value?
2) What do I need to do to change the struc values in a function?
C:
/***************************************************************************
 *                          button proof of concept                        *
 ***************************************************************************/
#include "allheaders.h"
// #include <stdio.h>

struct button {
  int  *btPtr;
  int       x;
  int       y;
} btExit;

void btExitFn ( struct button);

int main (  ) {

void ( *btExitPtr ) ( struct button ) = btExitFn;  // assign ptr to btExitFn addr

  btExit.btPtr = btExitPtr;           // bt func address
  btExit.x = 10;                      // init struct values
  btExit.y = 20;

  btExitFn ( btExit );                  // call btExit before x is 50
  btExitFn ( btExit );                  // call btExit after x is 50

  printf ("btExit addr   : %lu\n", btExitFn);    // fn addr
  printf ("btExitPtr     : %lu\n", btExitPtr); // ptr fn addr
  printf ("btExit.btPtr  : %lu\n", btExit.btPtr); // stored fn addr

  return 0;
}

void btExitFn ( struct button btExit ) {             
  printf ( "x = %d\n", btExit.x );
  btExit.x = 50;                                          //  <-- why not globally changed
  printf ( "x = %d\n\n", btExit.x );
}
 
Joined
Jul 16, 2023
Messages
8
Reaction score
3
I figured out my problem.
I failed to set the function and call for pointer types.
i.e btExitFn ( btExit ); should be btExitFn ( &btExit );
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,708
Latest member
SherleneF1

Latest Threads

Top