Question:
How to declare a functions inside the structures in C ?
janani
2010-07-01 04:34:50 UTC
I need to access the functions inside the structures , any one please guide me for accessing the functions inside the structures in C
Five answers:
Ratchetr
2010-07-01 05:08:17 UTC
As already mentioned, structures don't have functions.



But they can have pointers to functions. It's one way to (sort of) do object oriented programming in C.



// Define a function type

typedef void (*printfunc)(int);



// Define a struct with a pointer to function

typedef struct foo

{

printfunc func;

};



// A function

void print(int n)

{

printf("n=%d\n",n);

}



void main()

{



foo f; // instance of our struct

f.func = print; // set func to point to the print function

f.func(10); // call it

}
ussery
2016-12-11 19:23:41 UTC
Declare A Function In C
anonymous
2010-07-01 04:58:21 UTC
In C we don't have functions inside structures. But u can have them in C++, but its not a good practice to create functions inside structure as everything is public.
anonymous
2010-07-01 04:48:08 UTC
struct's in c store values.



these values are of the types defined when the struture is defined ie.

struct {

int members;

char* name;

}team;



to access these values you either use



team.members

OR

team->members



the '.' means that the structure is what team is.

the '->' means that the thing called team is a pointer to the structure.

('->' also can be obtained with *(team).members, ie shortcut)





these are the ways you access the data stored in a structure in c
anonymous
2010-07-01 04:43:51 UTC
Structures do not contain function, only variables. Classes can contain both, and more.

But then you are in C++, not C.



http://pages.cs.wisc.edu/~hasti/cs368/CppTutorial/NOTES/CLASSES-INTRO.html


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...