2013-07-05 61 views
1

下面的代碼提供了錯誤:的Arduino:結構指針作爲函數參數

sketch_jul05a:2: error: variable or field 'func' declared void 

所以我的問題是:我怎麼能傳遞一個指向結構作爲函數參數?

代碼:

typedef struct 
{ int a,b; 
} Struc; 


void func(Struc *p) { } 

void setup() { 
    Struc s; 
    func(&s); 
} 

void loop() 
{ 
} 

回答

5

的問題是,是,Arduino的IDE自動翻譯成這樣的C本:

#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() 
{ 
} 

這意味着Strucfunc聲明使用Struc前是C編譯器已知的。

解決方案:將Struc的定義移動到另一個頭文件幷包含它。

主要小品:

#include "datastructures.h" 

void func(Struc *p) { } 

void setup() { 
    Struc s; 
    func(&s); 
} 

void loop() 
{ 
} 

datastructures.h

struct Struc 
{ int a,b; 
}; 
0

上述工程的答案。在此期間我發現下面還工作,而不需要.h文件:

typedef struct MyStruc 
{ int a,b; 
} Struc; 

void func(struct MyStruc *p) { } 

void setup() { 
    Struc s; 
    func(&s); 
} 

void loop() 
{ 
} 

被警告:Arduino的編碼是有點片狀。許多圖書館也有點片!

0

這下面的代碼對我的作品在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 
    } 
} 
0

Prolly舊聞,但typedef struct允許成員函數(至少在IDE 1.6.4)。當然,這取決於你想要做什麼,但我想不出還有object.func(param pdata)也無法處理的任何func(struct *p)。就像p->a = 120;變得像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)); 
}