0

I was trying to pass PORTs address trough a struct by using a function, by i don't know how to correct work with pointers. Here's the code of my struct and function:

typedef struct {
read:1;
last_read:1;
changed:1;
unsigned short *port;    //Here the declaration of the pointer that will receive the address
pin:1;
active_state:1;
} Input;

void Setup_input(Input s,char *port, char pin, char active_state){
 s.port = &port;        //HERE I TRY TO PASS THE ADDRESS OF THE PORT TO THE POINTER OBJECT
 s.pin = pin;
 s.active_state = active_state;

It turns out that I'm not doing it correctly and I'm not able to read or control correctly the PORT. I'm using Mikroelectronic PRO compilers.

10 Rep
  • 2,217
  • 7
  • 19
  • 33
  • When you program microcontrollers it's recommended that you have passed the learning of the C language. – harper Dec 09 '14 at 08:01
  • You should really add a type, i.e. `unsigned int` to those bitfields. A 1-bit `int` is a bad idea. – unwind Dec 09 '14 at 08:12

1 Answers1

0

This line of code

s.port = &port;

stores the address of the parameter into the member port. When you dereference the pointer in the structure you will access the stack memory where the parameter port were while calling Setup_input(). This causes undefined behavior.

What you obviously want is to assigne the value of the parameter:

s.port = port;
harper
  • 13,345
  • 8
  • 56
  • 105
  • If i just fix that line could i use the member s.port as the original PORT was? i mean, could i read, write the PORT just using this member? – Matheus Garbelini Dec 09 '14 at 15:04
  • Yes, if you fixed your code than you use a copy of the pointer. As long as the data width is the same, it's okay. – harper Dec 09 '14 at 15:08
  • thank you a lot, i fixed a part, but i realized that my problem is with the struct argumento from mu function, if you look, my function is receiving the struct that i want to edit, but i think the function is creating a copy of the struct a pass to it. I need to someway pass a pointer of the orginal struct, so i could edit every struct i put in the funcion. do you know how can i declare a function with struct pointer? – Matheus Garbelini Dec 09 '14 at 16:39
  • `void Setup_input(Input *s, char *port, char pin, char active_state)` -- Frankly, buy a good C book (http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list/562377#562377). It makes much more fun to program microcontrollers if you can distinguish between a C language problem and a microcontroller problem. – harper Dec 09 '14 at 16:52