-3

I created a structure and wanted to assign the values to a Function Pointer of another structure. The sample code I wrote is like below. Please see what else I've missed.

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

struct PClass{

void *Funt;    

}gpclass;

struct StrFu stringfunc;

struct  StrFu{
    int a ;
    char c;

};

Initialise(){



}

main()
{
    stringfunc.a = 5;
    stringfunc.c = 'd';

    gpclass.Funt = malloc(sizeof(struct StrFu));

    gpclass.Funt = &stringfunc;
    memcpy(gpclass.Funt,&stringfunc,sizeof(struct StrFu));

printf("%u %u",gpclass.Funt->a,gpclass.Funt->c);

}
This isn't my real name
  • 4,869
  • 3
  • 17
  • 30
Kranthi
  • 1
  • 1

2 Answers2

2

There are several problems:

  1. A function pointer is not the same as void *, in fact you cannot rely on being able to convert between them.
  2. You shouldn't cast the return value of malloc() in C.
  3. You shouldn't call malloc(), then overwrite the returned pointer.
  4. You don't need to use malloc() to store a single pointer, just use a pointer.
  5. You shouldn't use memcpy() to copy structures, just use assignment.
  6. There are two valid main() prototypes: int main(void) and int main(int argc, char *argv[]), and you're not using either.
Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606
  • regarding 1. it does not look like he wants to use pointer to function, it is just the name of pointer misleading. anyway +1 – Dabo Feb 18 '14 at 11:37
  • Note of course that while the C standard does not require function pointers to be compatible with `void *`, there is a requirement in POSIX for this to be compatible. – This isn't my real name Feb 18 '14 at 23:05
0

there is lots of problem in your code , I try to correct it ,hope it will help

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct PClass{

void *Funt;

}gpclass;



struct  StrFu{
    int a ;
    char c;

};

struct StrFu stringfunc;

int main()
{
    stringfunc.a = 5;
    stringfunc.c = 'd';

    gpclass.Funt = malloc(sizeof(struct StrFu));

    gpclass.Funt = &stringfunc;
    memcpy(gpclass.Funt,&stringfunc,sizeof(struct StrFu));

    printf("%d %c",((struct StrFu*)gpclass.Funt)->a,((struct  StrFu*)gpclass.Funt)->c);
    return 0;
}

it outputs

5 d

michaeltang
  • 2,850
  • 15
  • 18
  • -1, keeps the broken `main()`, the pointless `malloc()`, the the super-pointless `memcpy()`. Very bad answer, imo. – unwind Feb 18 '14 at 11:24
  • @Micheal: If I need to copy the information of this generic pointer into a buffer ,(char *buffer). How to achieve ? – Kranthi Feb 19 '14 at 15:19
  • memcpy(buffer, (struct StrFu*)gpclass.Funt, sizeof(gpclass.Funt)) will copy only the pointer instead of data, right? – Kranthi Feb 19 '14 at 15:21