JCSB
JCSB

Reputation: 385

set values of a struct pointer to a struct

Is it possible to set the values of a struct pointer in a struct? I get an error and cannot typecast myStruct* into myStruct.

typedef struct {
   int foo;
   int bar;
} myStruct;

int main() {

myStruct *pS;

myStruct S1 = {0,0};

myStruct S2;

pS = S1;

S2 = pS;   // I get an error there, cannot set struct pointer to a   struct
}

Upvotes: 0

Views: 305

Answers (1)

geobreze
geobreze

Reputation: 2422

So, in your example, you have pointer pS and regular variable S1.

A pointer is a variable that stores the memory address as its value.

Variable is the name of memory location.

So, the difference between regular variable is that variable stores value of an object, but pointer stores memory address of an object.

There are operators which allow getting object's address and getting object value by it's address:

  • Address-of operator &. &a will return address of object a.
  • Dereference operator *. *p will return object stored by address p.

Thus, in your code you should get two errors:

pS = S1; // error: Trying to assign struct value to a pointer

S2 = pS; // error: Trying to assign pointer to a struct value

To fix this, you should assign address to a pS and value to S2

typedef struct {
   int foo;
   int bar;
} myStruct;

int main() {

myStruct *pS;

myStruct S1 = {0,0};

myStruct S2;

pS = &S1; // getting address of S1

S2 = *pS; // getting value stored by address pS
}

Upvotes: 1

Related Questions