I am trying to use a function pointer inside a struct, whereas the function pointer needs an instance of the struct itself as argument. My current code snippet looks like this:
#include "stdio.h"
#include "stdint.h"
typedef struct MYSTRUCT_S MYSTRUCT;
typedef struct {
int (*isInRange)(const MYSTRUCT* pDataPoint, const uint16_t newValue);
const uint16_t minValue;
const uint16_t maxValue;
} MYSTRUCT_S;
int isInRange(const MYSTRUCT* pDataPoint, const uint16_t newValue) {
MYSTRUCT* mDatapoint = (MYSTRUCT*)pDataPoint;
if ((newValue < mDatapoint->minValue) || (newValue > mDatapoint->maxValue)) {
return 0;
} else {
return 1;
}
}
int main() {
static MYSTRUCT* maDataPoint = NULL;
maDataPoint->isInRange(maDataPoint, 6);
return 0;
}
The compiler complains about: error: invalid use of incomplete typedef 'MYSTRUCT' {aka 'struct MYSTRUCT_S'}"
I was already reading through the following items, but could not find the solution for my issue:
- Function pointer as a member of a C struct
- "this" pointer in C (not C++)
- forward declaration of a struct in C?
Any idea, how I could solve this issue?
MYSTRUCT* mDatapoint = (MYSTRUCT*)pDataPoint;? Just usepDataPointin the rest of the function.struct MYSTRUCT_Sanywhere. You defineMYSTRUCT_Sas a typedef to an anonymous struct.typedef struct {totypedef struct MYSTRUCT_S {#include "stdio.h"use#include <stdio.h>etc., unless you plan to supply your own versions locally.