I have the following structure definitions:
typedef struct S_t S_t;
struct S_t {
float *s_ptr;
uint32_t ns;
};
typedef struct p_t p_t;
struct p_t {
int32_t pID;
float pVal;
};
typedef struct pr_t pr_t;
struct pr_t {
S_t *S;
int (*TrimS)(S_t *TS, int sSize);
p_t *TP;
};
I also have the following function defined:
int success = 0;
int failure = -1;
int ChopS(S_t *TS, int size)
{
int i, c;
for(i = 0; i < TS->ns; i )
{
if (i >= size)
TS->s_ptr[i] = 0.0;
}
c = 0;
for(i = 0; i < TS->ns; i )
{
if(TS->s_ptr[i] == 0.0)
c ;
}
if (c == size)
return success;
else
return failure;
}
I do the following (full code here) to assign values to each member of type pr_t
, one of whose member is TrimS
which is a status flag function pointer:
p_t *p2 = NULL;
S_t *tS2 = NULL;
tS2 = malloc(sizeof(S_t));
pr_t *SP2 = NULL;
SP2 = malloc(sizeof(pr_t));
p2 = (p_t *) malloc(sizeof(p_t));
SP2->S = tS2;
SP2->TP = p2;
SP2->TrimS = ChopS;
SP2->TrimS(tS2, 8);
If I try to access the value of the flag using SP2->TrimS
, I get a junk value (or an address value I think) but not 0
or -1
as I expect. What is exactly happening over here? How can I access the value set by ChopS
in SP2->TrimS
?
CodePudding user response:
You need to call the function to get the return value. It is not stored anywhere and the function pointer does not store the last return value. Use it as any "normal" function
if(SP2->TrimS(tS2, 8) == failure)
{
/* do something */
}
else
{
/* do something else */
}
or if you want to access it later (after the call) you need to store it in the variable or have an additional struct member to store it:
struct pr_t {
S_t *S;
int (*TrimS)(S_t *, int);
int last_TrimS_Return_Value;
p_t *TP;
};
/* .... */
SP2 -> last_TrimS_Return_Value = SP2->TrimS(tS2, 8);