C Programming Pointers To Structures

Last modified by Microchip on 2023/11/09 09:06

Syntax

If typeName or structName has already been defined:

typeName *ptrName;
-or-
struct structName *ptrName;

Example 1

1  typedef struct
2  {
3   float re;    
4   float im;    
5  } complex;       
6  ...
7  complex *p;

Example 2

1 struct complex
2 {
3  float re;    
4  float im;    
5 }       
6 ...
7 struct complex *p;

Using a Pointer to Access Structure Members

Syntax

If ptrName has already been defined

ptrName -> memberName

Pointer must first be initialized to point to the address of the structure itself: ptrName = &structVariable;

Example: Definitions

1 typedef struct
2 {
3  float re;    
4  float im;    
5 } complex;  complex type
6 ...
7 complex x;  complex var
8 complex *p; ptr to complex

Example: Usage

1 int main(void)
2 {
3  p = &x;
4  Set x.re = 1.25 via p
5  p->re = 1.25;
6  Set x.im = 2.50 via p
7  p->im = 2.50;
8 }