LamaCoder LamaCoder - 4 days ago 5
C Question

function pointer not working for int

Im trying to use the power of function pointers, it all went fine until i tried to make the function pointer use a 2nd argument as type int.

The code below generates an error, which is displayed below
In an header file:

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct UnitTag {
int x;
int y;
void (*move)(Unit, int);
} Unit;


Error:

error: expected ‘)’ before ‘int’
void (*move)(Unit, int);
^


void (*move)(Unit); works all fine, which surprises me how adding an argument can cause an error.

I call my struct in a C file, by including header and then doing:
Unit units[UNITCOUNT];
units[0].move(&units[0], 1);

Update:

adding:

typedef struct UnitTag Unit


Causes the error to dissapear, however I can no longer use the function as before.

error: incompatible type for argument 1 of ‘units[i].move’
units[0].move(&units[0], 0);
^


note: expected ‘Unit’ but argument is of type ‘struct UnitTag *’

LPs LPs
Answer

If I'm getting you, you can simply use struct keyword:

#include <stdio.h>

typedef struct UnitTag {
    int x;
    int y;
    void (*move)(struct UnitTag, int);
} Unit;

void Test (struct UnitTag test1, int test2)
{
    printf("Test1.x: %d\n", test1.x);
    printf("Test1.y: %d\n", test1.y);
    printf("Test2  : %d\n", test2);
}

int main(void)
{
    Unit units[100];

    units[0].move = Test;
    units[0].x    = 1;
    units[0].y    = 2;

    units[0].move(units[0], 3);
}

Output:

Test1.x: 1
Test1.y: 2
Test2  : 3

If you want to pass struct by referebce, simply:

#include <stdio.h>

typedef struct UnitTag {
    int x;
    int y;
    void (*move)(struct UnitTag*, int);
} Unit;

void Test (struct UnitTag *test1, int test2)
{
    test1->x = 4;
    test1->y = 5;
}

int main(void)
{
    Unit units[100];

    units[0].move = Test;
    units[0].x    = 1;
    units[0].y    = 2;

    units[0].move(&units[0], 3);

    printf("units[0].x: %d\n", units[0].x);
    printf("units[0].y: %d\n", units[0].y);
}

Output is:

units[0].x: 4
units[0].y: 5
Comments