Expected identifier before token in function pointer - c

typedef enum
{
TCP = 1,
UDP
}protocol;
typedef enum
{
DLL_Operation = 1,
MT_Operation,
Fork_Operation,
IPC_Operation
}msgc;
struct f
{
int seqNo;
protocol p;
msgc m;
protocol q;
int PayLoadSize;
void (*payload_ptr)();
};
This is my structure which i am using...
Now i am assigning address of function in that function pointer defining in strucutre...
if(f2.m == 1)
{
f2.(*payload_ptr) = DLL;
f2.payload_ptr();
}
else if(f2.m == 2)
{
f2.(*payload_ptr) = MT;
f2.payload_ptr();
}
else if(f2.m == 3)
{
f2.(*payload_ptr) = Fork;
f2.payload_ptr();
}
else
{
f2.(*payload_ptr) = IPC;
f2.payload_ptr();
}
in compiling this program... it is showing error like..
error: expected identifier before ‘(’ token
f2.(*payload_ptr) = DLL;
& same for all condition.... what is the solution..
this DLL, MT all are some function which i define for certain operation...

You are assigning the values to function pointers wrongly.
It should be like below for all the cases
if(f2.m == 1)
{
f2.payload_ptr = DLL;
f2.payload_ptr();
}
Please ensure that functions like DLL are of type void DLL();

Related

How can I return 2 numbers from a function

I have to copy paste this exact code below into 3 separate functions (juice function, milk function and buy function). So I thought, why not make another function called array_checker and call it in toe juice, milk and buy function instead of the copy pasting the code. However, the function (copy pasted code) needs to return 2 things. int item_used and int buy_now. How can I do this?
This is the code I copy paste:
if (item_sale == 1) {
item_used = TRUE;
buy_now = legal_cards[0];
} else {
item_used = FALSE;
}
There are two general approaches to this:
Create a struct with two int members to return from your function - this is fine when two values that you return are easy to copy, e.g. a pair of ints, or
Take a pointer for one or both variables - this lets you avoid copying, but requires the caller to allocate storage for the result upfront.
Here is an example of the first approach:
struct buy_decision {
int item_used;
int buy_now;
};
buy_decision milk(...) {
buy_decision res;
if (item_sale == 1) {
res.item_used = TRUE;
res.buy_now = legal_cards[0];
} else {
res.item_used = FALSE;
res.buy_now = 0;
}
return res;
}
Here is an example of the second approach with buy_now taken by pointer:
int milk(..., int* buy_now_ptr) {
if (item_sale == 1) {
*buy_now_ptr = legal_cards[0];
return TRUE;
}
return FALSE;
}
Well, you can return an array with both numbers.
To return multiple values from a function, create one structure, put the member whatever you want into this & return the structure variable. for e.g
typedef struct buy_fun_info {
int item_used;
int buy_now;
}BUY;
In array_checker() function, create the variable of above structure, fill the members & return those. for e.g
BUY array_checker() { /*array_checker() function */
BUY obj;
obj.buy_now = legal_cards[0];
obj.item_used = FALSE;
return obj;/* return structure variable */
}
Above I tried to explain with sample example, you need to modify accordingly.
You have to either define a structure to return :
struct itemStuff {
int itemUsed;
int buy_now;
}
then
struct itemStuff myItemFunction(...) {
struct itemStuff myItem;
(...)
if (item_sale == 1) {
myItem.item_used = TRUE;
myItem.buy_now = legal_cards[0];
} else {
myItem.item_used = FALSE;
}
return myItem;
}
The caller of the function will have to create the same struct to receive the return data
struct itemStuff thisItem = myItemFunction(...);
or use pass-by reference to pass in modifiable arguments
void myItemFunction(..., int *item_used, int *buy_noe) {
if (item_sale == 1) {
*item_used = TRUE;
*buy_now = legal_cards[0];
} else {
*item_used = FALSE;
}
}
Here, the caller will have to pass in the address of two integers to be set :
int used;
int buy;
myItemFunction(..., &used, &buy);

Initializing a struct in C

Im having trouble initialising structures (well doing everything actually, but structures first). The struct is first made in a header as follows
typedef enum cell
{
BLANK, RED, CYAN
} Cell;
#define NAMELEN 20
typedef struct player
{
char name[NAMELEN + NULL_SPACE];
Cell token;
unsigned score;
} Player;
void initFirstPlayer(Player * player);
void initSecondPlayer(Player * player, Cell token);
#endif
=======================================================================
and I tried to initialise it here
void initFirstPlayer(Player * player)
{
int randNo = rand() % 2;
if (randNo == 0) {
token = RED;
}
else() {
token = CYAN;
}
player ; p1 = {
"placeholder",
token,
0,
}
}
void initSecondPlayer(Player * player, Cell token)
{ }
What is the correct way to initialise this player struct?
I suspect this should work for you. Use a generic initPlayer function. Use that to allocate memory for the player and set the initial values. Be sure to also include a freePlayer function where you free() the player when you're done.
#include <stdlib.h>
#include <string.h>
Player* initPlayer()
{
Player* player = malloc(sizeof(Player));
int randNo = rand() % 2;
if (randNo == 0) {
player->token = RED;
}
else {
player->token = CYAN;
}
const char* initName = "placeholder";
strcpy(player->name, initName);
player->score = 0;
return player;
}
void freePlayer(Player* p)
{
free(p);
}
The way you'd use this would be like so:
int main()
{
Player* p1 = initPlayer();
Player* p2 = initPlayer();
play(p1, p2);
freePlayer(p1);
freePlayer(p2);
}
Assuming you have at least C99 support, so that compound literals and designated initializers are available to you, then you can use:
void initFirstPlayer(Player *player)
{
*player = (Player){ .token = rand() % 2 ? CYAN : RED,
.score = 0,
.name = "placeholder"
};
}
This does a structure assignment to the variable whose address is passed to the function. It compresses it all into one statement; you can split it out into several if you wish. This is an occasion where the ternary ? : operator is useful. You might prefer (rand() % 2) with the extra parentheses; I'd probably add them as often as I'd omit them.
The compound literal comes from (typename){ ...initializer for typename... }.
The designated initializers are the .member = value notations.
If you're stuck with C90 support, you have to work harder, perhaps creating a local variable with the correct information and then doing the structure assignment.
void initFirstPlayer(Player *player)
{
Player p1 = { "placeholder", rand() % 2 ? CYAN : RED, 0 };
*player = p1;
}
Now the onus is on you to list the initializers in the correct sequence.
Another way is to receive the player you want to inicialize as parameter:
void initPlayer(Player* player)
{
int randNo = rand() % 2;
if (randNo == 0) {
player->token = RED;
}
else {
player->token = CYAN;
}
const char* initName = "placeholder";
strcpy(player->name, initName);
player->score = 0;
}
int main() {
Player p1;
initPlayer(&p1);
}
You can have an array of players or allocate dinamically with malloc.

Return a union in C, but make it look nice

So, I have a union:
typedef union {
int intVal;
char charVal;
bool boolVal;
} myUnion_t;
And I have a function, foo, (in the same file as the latter union) which will return myUnion_t.
I obviously could do:
myUnion_t foo(int n){
myUnion_t rtn;
if(n == 0){
rtn.intVal = 1;
} else if(n == 1){
rtn.charVal = 'b';
} else {
rtn.boolVal = false;
}
return rtn;
}
But this is rather messy; my CDO doesn't like it. Is there a nicer way to do this, something like:
myUnion_t foo(int n){
if(n == 1){
return 1;
} else if(n == 2){
return 'b';
} else {
return false;
}
}
EDIT: Okay, unions are inherently messy. Thanks for your help, I'll just do it the normal way :)
Although you cannot return a value of a union member in place of a union itself, you could use compound literals of C99 to avoid declaring the union at the top and setting its fields outside initializer:
typedef union object_t {
int intVal;
char charVal;
_Bool boolVal;
} object_t;
object_t foo(char ch){
switch(ch) {
case 'a': return (object_t) { .intVal = 4 };
case 'b': return (object_t) { .charVal = 'b' };
default: return (object_t) { .boolVal = true };
}
}
The reason you need to use compound literal is that the type by itself is insufficient to identify the member of a union that you would like to be assigned.

Error when compiling for MicroChip 'invalid operands to binary =='

static int handle_put_light(coap_rw_buffer_t *scratch, const coap_packet_t *inpkt,coap_packet_t *outpkt, uint8_t id_hi, uint8_t id_lo)
{
if (inpkt->payload.len == 0)
return coap_make_response(scratch, outpkt, NULL, 0, id_hi, id_lo, COAP_RSPCODE_BAD_REQUEST, COAP_CONTENTTYPE_TEXT_PLAIN);
if (inpkt->payload.p[0] == '1')
{
light = '1';
UARTWrite(1,"ON\n");
return coap_make_response(scratch, outpkt, (const UINT8_VAL *)&light, 1, id_hi, id_lo, COAP_RSPCODE_CHANGED, COAP_CONTENTTYPE_TEXT_PLAIN);
}
else
{
light = '0';
UARTWrite(1,"OFF\n");
return coap_make_response(scratch, outpkt, (const UINT8_VAL *)&light, 1, id_hi, id_lo, COAP_RSPCODE_CHANGED, COAP_CONTENTTYPE_TEXT_PLAIN);
}
}
This is my code and i am getting error on line no.5 . The struct is defined as
typedef struct
{
coap_header_t hdr;
coap_buffer_t tok;
uint8_t numopts;
coap_option_t opts[MAXOPT];
coap_buffer_t payload;
} coap_packet_t;
typedef struct
{
const UINT8_VAL *p;
size_t len;
} coap_buffer_t;
I am getting the following error when i try to compile using Microchip c30 compiler which is primarily C compiler.
Error :- error: invalid operands to binary ==
Please HElp me !!
Try using the Val member of UINT8_VAL for comparison:
inpkt->payloadp[0].Val == '1'

Compile error when creating packet

I'm studying THIS tutorial for tinyos and I wanted to try it out. I try to create the packet but it gives me the following error. I don't know what's wrong. It is probably something simple but I can't figure out what it is.
#include "TestMsg.h"
...
event void AMControl.startDone(error_t error) {
if (error == SUCCESS) {
call Leds.led0On();
//create packet
TestMsg_t* msg = call Packet.getPayload(&packet, sizeof(TestMsg_t));
msg->NodeID = TOS_NODE_ID;
//
// //TODO in the meantime this can change
// button_state_t val = call Get.get();
// msg->Data = ( val == BUTTON_PRESSED ? 1 : 0 );
//
// //send packet
// if (call AMSend.send(AM_BROADCAST_ADDR, &packet, sizeof(TestMsg_t)) == SUCCESS) {
// radioBusy = TRUE;
// }
} else {
call AMControl.start();
}
}
...
Here is TestMsg.h
#ifndef TEST_MSG_H
#define TEST_MSG_H
typedef nx_struct _TestMsg {
nx_uint16_t NodeID;
nx_uint8_t Data;
} TestMsg_t;
enum {
AM_RADIO = 6
};
#endif /* TEST_MSG_H */
Here is the part where it is declared in the video
The error I get it this:
In file included from /home/advanticsys/ws/TestRadio/src/TestRadioAppC.nc:5:
In component `TestRadioC':
/home/advanticsys/ws/TestRadio/src/TestRadioC.nc: In function `AMControl.startDone':
/home/advanticsys/ws/TestRadio/src/TestRadioC.nc:43: syntax error before `*'
/home/advanticsys/ws/TestRadio/src/TestRadioC.nc:44: `msg' undeclared (first use in this function)
/home/advanticsys/ws/TestRadio/src/TestRadioC.nc:44: (Each undeclared identifier is reported only once
/home/advanticsys/ws/TestRadio/src/TestRadioC.nc:44: for each function it appears in.)
Update
Something is wrong with structs and headers.
#include "Szar.h"
#include "BarType.h"
module SzarP {
uses interface Boot;
uses interface Leds;
}
implementation {
event void Boot.booted() {
// TODO Auto-generated method stub
call Leds.led0On();
Szar_t foo;
Szar_t *szar = &foo;
BarType_t barVar;
barVar.data = 0;
BarType_t *pBarVar = &barVar;
pBarVar->data = 1;
}
}
Here are the 2 header files.
#ifndef SZAR_H
#define SZAR_H
typedef nx_struct _Szar {
nx_uint8_t szar1;
nx_uint16_t szar2;
} Szar_t;
#endif /* SZAR_H */
#ifndef BAR_TYPE_H
#define BAR_TYPE_H
typedef struct _BarType {
uint8_t id;
uint32_t data;
} BarType_t;
#endif /* BAR_TYPE_H */
And the errors:
In file included from /home/advanticsys/ws/Szar/src/SzarAppC.nc:6:
In component `SzarP':
/home/advanticsys/ws/Szar/src/SzarP.nc: In function `Boot.booted':
/home/advanticsys/ws/Szar/src/SzarP.nc:15: syntax error before `foo'
/home/advanticsys/ws/Szar/src/SzarP.nc:19: `barVar' undeclared (first use in this function)
/home/advanticsys/ws/Szar/src/SzarP.nc:19: (Each undeclared identifier is reported only once
/home/advanticsys/ws/Szar/src/SzarP.nc:19: for each function it appears in.)
/home/advanticsys/ws/Szar/src/SzarP.nc:20: syntax error before `*'
/home/advanticsys/ws/Szar/src/SzarP.nc:21: `pBarVar' undeclared (first use in this function)
For some strange reason I have to declare EVERY variable outside the function, and then it works. Example:
bool radioBusy = FALSE;
message_t packet;
TestMsg_t *messageToSend;
button_state_t buttonState;
event void AMControl.startDone(error_t error) {
if (error == SUCCESS) {
call Leds.led0On();
messageToSend = call Packet.getPayload(&packet, sizeof(TestMsg_t));
messageToSend->NodeID = TOS_NODE_ID;
//TODO in the meantime this can change
buttonState = call Get.get();
messageToSend->Data = ( buttonState == BUTTON_PRESSED ? 1 : 0 );
//send packet
if (call AMSend.send(AM_BROADCAST_ADDR, &packet, sizeof(TestMsg_t)) == SUCCESS) {
radioBusy = TRUE;
}
} else {
call AMControl.start();
}
}
It also works if I declare my variables at the beginning of the functions/events/commands without any code before them.

Resources