struct and function pointer in C

S

subramanian100in

Can a structure contain function pointers as members ?
If so, where is it useful ?
 
R

Richard Heathfield

(e-mail address removed), India said:
Can a structure contain function pointers as members ?
Yes.

If so, where is it useful ?

It's useful in cases where you need to associate a function pointer with
other data.
 
N

newsGroups

ya we can do this .like

struct abc
{
int a;
char name[10];
int *(functionptr)(int,int);
}n,m;
 
F

Flash Gordon

Roland Pibinger wrote, On 22/02/07 20:18:
The following article may give some ideas. It is not perfect and may
be improved but it shows one way to program polymorphically in C:
http://www.codeproject.com/cpp/PolymorphismC.asp

It certainly needs some work. It uses a macro name which is an
underscore followed by a capital in the header, and such names are
reserved for the implementation. It uses the form
type *ptr = (type *)malloc(sizeof(type));
instead of the simpler and more robust
type *ptr = (type *)malloc(sizeof(type));


Also not specifying in prototypes when functions do not take parameters.

I've not actually downloaded the code to check the rest of it.
 
C

CBFalconer

Flash said:
.... snip ...

It certainly needs some work. It uses a macro name which is an
underscore followed by a capital in the header, and such names
are reserved for the implementation. It uses the form

type *ptr = (type *)malloc(sizeof(type));
instead of the simpler and more robust
type *ptr = (type *)malloc(sizeof(type));

I think you failed to complete the editing :) I fail to see any
gains in simplicity or robustness. Here's something to cut and
paste:

type *ptr = malloc(sizeof *ptr);
 
K

Keith Thompson

Flash Gordon said:
Roland Pibinger wrote, On 22/02/07 20:18:

It certainly needs some work. It uses a macro name which is an
underscore followed by a capital in the header, and such names are
reserved for the implementation. It uses the form
type *ptr = (type *)malloc(sizeof(type));
instead of the simpler and more robust
type *ptr = (type *)malloc(sizeof(type));

Simpler, more robust, and identical.

I presume you meant:

type *ptr = malloc(sizeof *ptr);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top