Pointers to Structures
Syntax
If typeName or structName has already been defined:
typeName *ptrName;
-or-
struct structName *ptrName;
Example 1
|
1
2
3
4
5
6
7
|
typedef struct{ float re; float im; } complex; ...complex *p; |
Example 2
|
1
2
3
4
5
6
7
|
struct complex{ float re; float im; } ...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
2
3
4
5
6
7
8
|
typedef struct{ float re; float im; } complex; //complex type ...complex x; //complex varcomplex *p; //ptr to complex |
Example: Usage
|
1
2
3
4
5
6
7
8
|
int main(void){ p = &x; //Set x.re = 1.25 via p p->re = 1.25; //Set x.im = 2.50 via p p->im = 2.50; } |