Pointers to struct assignment

Status
Not open for further replies.

alexz

Full Member level 5
Joined
Nov 19, 2004
Messages
283
Helped
6
Reputation
12
Reaction score
3
Trophy points
1,298
Location
UK
Activity points
2,246
struct assignment

A well known method to make a code flexible and divide the project in to objects is to use pointers to functions in a struct and then initialize the struct with pointers to the functions you want to use.

typedef struct myStructType
{
void (*myFunc)(void);
}myStruct;

void func1(void)
{
}

void main(void)
{
myStruct struct1;

struct1.myFunc = func1; //assign the func pointer
struct1.myFunc(); //call function func1
}

This allows using the same struct for different functions at a time.

Now, the question is how to do the similar thing to other structs rather then to functions.
I want to have a pointer to a struct in a struct. And then being able to initialize this pointer to a struct I want to use.

struct oneStruct
{
char var1;
}one;

struct twoStruct
{
char var1;
}two;

typedef struct basic
{
structType structPtr; //??????????????
}structBasic;

void main(void)
{
structBasic.structPtr = &oneStruct; //set the pointer to a struct I want to use

structBasic.structPtr->var1++;
}
 

struct assignment from pointer

Code:
typedef struct
{
int a;
int b;
}BASIC;

BASIC B_one, B_two;  /* Global */

typedef struct
{
BASIC *structpointer;
}VARIABLE;

void main(void)
{
BASIC B_three;  /* or local */
VARIABLE V;

V.structpointer = &B_one;

}

Try something like this.
 

Status
Not open for further replies.

Similar threads

Cookies are required to use this site. You must accept them to continue using the site. Learn more…