The code below gives the error:
sketch_jul05a:2: error: variable or field 'func' declared void
So my question is: how can I pass a pointer to a struct as a function parameter?
Code:
typedef struct
{ int a,b;
} Struc;
void func(Struc *p) { }
void setup() {
Struc s;
func(&s);
}
void loop()
{
}
The problem is, that the Arduino-IDE auto-translates this into C like this:
#line 1 "sketch_jul05a.ino"
#include "Arduino.h"
void func(Struc *p);
void setup();
void loop();
#line 1
typedef struct
{ int a,b;
} Struc;
void func(Struc *p) { }
void setup() {
Struc s;
func(&s);
}
void loop()
{
}
Which means Struc
is used in the declaration of func
before Struc
is known to the C compiler.
Solution: Move the definition of Struc
into another header file and include this.
Main sketch:
#include "datastructures.h"
void func(Struc *p) { }
void setup() {
Struc s;
func(&s);
}
void loop()
{
}
and datastructures.h
:
struct Struc
{ int a,b;
};
The answer above works. In the meantime I had found the following also to work, without the need for a .h file:
typedef struct MyStruc
{ int a,b;
} Struc;
void func(struct MyStruc *p) { }
void setup() {
Struc s;
func(&s);
}
void loop()
{
}
Be warned: Arduino coding is a little flaky. Many of the libraries are also a bit flaky!
This next code works for me as in Arduino 1.6.3:
typedef struct S
{
int a;
}S;
void f(S * s, int v);
void f(S * s, int v)
{
s->a = v;
}
void setup() {
}
void loop() {
S anObject;
// I hate global variables
pinMode(13, OUTPUT);
// I hate the "setup()" function
f(&anObject, 0);
// I love ADTs
while (1) // I hate the "loop" mechanism
{
// do something
}
}
Prolly old news, but typedef struct
allows member functions (at least in IDE 1.6.4). Depending on what you want to do, of course, but I can't think of any func(struct *p)
that couldn't be handled also with object.func(param pdata)
. Just that something like p->a = 120;
becomes something like object.setA(120);
typedef struct {
byte var1;
byte var2;
void setVar1(byte val){
this->var1=val;
}
byte getVar1(void) {
return this->var1;
}
} wtf;
wtf testW = {127,15};
void initwtf(byte setVal) {
testW.setVar1(setVal);
Serial.print("Here is an objective returned value: ");
Serial.println(testW.getVar1());
}
...
void loop() {
initwtf(random(0,100));
}