C Structures

The use of structures, also known as structs, allows you to collect numerous related variables in a single location. A member of the structure is referred to as each variable in it.

Unlike an array, a structure can contain many different data types.


Code:


  #include 
  // Create a structure called myStructure
  struct myStructure {

      int myNum;
      char myLetter;

  };

  int main() {

  // Create a structure variable of myStructure called s1
  struct myStructure s1;

  // Assign values to members of s1
  s1.myNum = 13;
  s1.myLetter = 'B';

  // Print values
  printf("My number: %d\n", s1.myNum);
  printf("My letter: %c\n", s1.myLetter);
  return 0;
  }


Output

My Number : 13 My Letter : B

Explanation:

The struct keyword is used to create a structure, and curly brackets are used to declare each member of the structure. You must make a variable of the structure in order to access it.


Use the struct keyword inside the main() method, followed by the name of the structure and then the name of the structure variable.


To access members of a structure, use the dot syntax (.)







© Copyright 2022 Advanced PLC. All rights reserved.