Forum: Compiler & IDEs optionaler fuctionspointer im struct


von Reiner W. (reiner_w)


Lesenswert?

In meinem aktuellen Projekt hab ich mit mehreren Protokollen zu tun, die 
hab ich jeweils in ein struct gepackt und die structs dann in ein array.
Soweit ist alles gut. Nun gibt es ein Protokoll, dass noch erweiterte 
Funktionen bietet.
1
//store data to buffer for different protocols****************************
2
void common_func1_protocol1 (void) {
3
     //mach was 
4
}
5
void common_func2_protocol1(void){
6
     //mach was anderes 
7
}
8
9
void extended_func1_protocol1 (void) {
10
     //mach was 
11
}
12
13
//************************************************************************
14
15
typedef struct protocol {
16
    uint8 member1;
17
    void (*common_func)(void);
18
    void (*extended_func)(void);   
19
} PROTOCOL_t;    
20
21
22
PROTOCOL_t protocol_protocol1 = {
23
    .member1 = 1,        
24
    .common_func = common_func1_protocol1 
25
    .extended_func = extended_func1_protocol1
26
};
27
PROTOCOL_t protocol_protocol2 = {
28
    .member1 = 10, 
29
    .common_func = common_func2_protocol1 
30
};
31
32
PROTOCOL_t protocols[2];
33
34
//init the protocol array
35
protocols[0] = protocol_protocol1;
36
protocols[1] = protocol_protocol2;
37
38
//call
39
protocols[1].common_func()
40
41
//pseudo code
42
wenn protocols[1].extended_func vrhanden
43
     protocols[1].extended_func()

Ich habe 2 Fragen dazu.

1. Kann ich im struct protocol_protocol2 extended_func uninitialisiert 
lassen?

2. Wie kann ich beim Aufruf feststellen, ob extended_func belegt ist ?

Ich habe natürlich die Möglichkeit eine dummy Funktion für 
protocol_protocol2 anzulegen, aber geht das nicht besser ?

Hoffe, ich habe meine Frage verständlich gestellt.

: Bearbeitet durch User
von Bastler (Gast)


Lesenswert?

Mit NULL initialisieren und
1
if(protocols[1].extended.func!=NULL)
2
   protocols[1].extended.func();

von OldMan (Gast)


Lesenswert?

Zu
1. Ja, kannst Du, solltest Du aber nicht wegen 2. Zumindest auf NULL 
setzen.

2. Indem Du vorher auf ungleich NULL abfragst. Bzw., wenn der Pointer 
nicht
   initialisiert ist, prüfst, ob der Zeiger auf Deine Funktion zeigt.
   Also die Adresse stimmt.
   Auf NULL abzufragen, finde ich eleganter.

von Reiner W. (reiner_w)


Lesenswert?

@Bastler, @OldMan Tausend Dank euch Beiden
Genau das hab ich gesucht.

Wunderschönes Wochenende
Reiner

Bitte melde dich an um einen Beitrag zu schreiben. Anmeldung ist kostenlos und dauert nur eine Minute.
Bestehender Account
Schon ein Account bei Google/GoogleMail? Keine Anmeldung erforderlich!
Mit Google-Account einloggen
Noch kein Account? Hier anmelden.