Advertisement
igendel

C Access to a struct in array through a pointer

Sep 20th, 2021
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.46 KB | None | 0 0
  1. #include <stdint.h>
  2. #include <stdio.h>
  3.  
  4. struct tMyStruct {
  5.    
  6.     uint8_t var1;
  7.     uint32_t var2;
  8.    
  9. }  myStruct[10], *pMyStruct[10];
  10.  
  11.  
  12. int main(void) {
  13.  
  14.     uint8_t n;
  15.    
  16.     // Initialize pointer array
  17.     for (n = 0; n < 10; n++)
  18.         pMyStruct[n] = &myStruct[n];
  19.        
  20.     // Direct access
  21.     myStruct[5].var1 = 123;
  22.     printf("%d\n", myStruct[5].var1);
  23.    
  24.     // Access through pointer
  25.     pMyStruct[5]->var1 = 124;
  26.     printf("%d\n", myStruct[5].var1);
  27.  
  28.     return 0;
  29.  
  30. }
  31.  
  32.  
  33.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement