Billa
Billa

Reputation: 327

Accessing data inside a struct

I want to access information inside a struct if somebody can help me out here.

typedef struct {        
    int time;       
    char sat,rcv;  
    char LLI [3];
} obsd_t;


typedef struct {                
    obsd_t *data;      
} obs_t;

I have something like

obs_t obs;
int x;

Now I want to assign x to the value of time in obsd_t so what should I do. Is something like this correct

x=obs.data.time;

p.s I looked over other threads of stackoverflow but could not understand from there. Some did not have any accepted answer so I was reluctant

Upvotes: 4

Views: 26580

Answers (6)

yulian
yulian

Reputation: 1627

Access to the data as a pointer to a struct using -> operator:

x = obs.data->time;

or

Access to the address of the data using * operator (dereferencing the pointer):

x = obs.(*data).time

Both variants are right.

Read this for more detailes: Pointers and Structures

Upvotes: 2

Dariusz
Dariusz

Reputation: 22241

If you want to access the struct like this: x=obs.data.time; you have to declare your obs_t differently, like that:

typedef struct {                
    obsd_t data;      
} obs_t;

Please familiarize yourself with how pointers work so that you can avoid such problems in the future.

Upvotes: 2

nouney
nouney

Reputation: 4411

data is a pointer to a obsd_t struct. You have to use the operator -> instead of . to access the elements of a structure referenced by a pointer:

x = obs.data->time;

Upvotes: 3

Yu Hao
Yu Hao

Reputation: 122363

You should use this instead:

x = obs.data->time;

because data in obs_t is a pointer.

In general, assume strcut foo* p;, then to access element bar in struct foo

(*p).bar

and

p->bar

are the same

Upvotes: 5

0xF1
0xF1

Reputation: 6116

You are mixing a pointer with a variable. Use . operator for struct variables (e.g. obs) and use -> for pointers (e.g. for data)

i.e.

x = obs.data->time

or you can also use like this as suggested by Yu Hao

x = obs.(*data).time

Upvotes: 11

Paul R
Paul R

Reputation: 212929

You just need to do it like this:

x=obs.data->time;

(This assumes of course that you have initialised obs.data to point at a valid instance of obsd_t.)

Upvotes: 4

Related Questions