C Structures


When programming, it is often convenient to have a single name with which to refer to a group of a related values. Structures provide a way of storing many different values in variables of potentially different types under the same name.

Example 1

struct database 
  int id_number;
  int age;
  float salary;
int main()
  struct database employee;  /* There is now an employee variable that has
                              modifiable variables inside it.*/
  employee.age = 22;
  employee.id_number = 1;
  employee.salary = 12000.21;

Example 2

#include <stdio.h>
struct xampl {
  int x;
int main()
    struct xampl structure;
    struct xampl *ptr;
    structure.x = 12;
    ptr = &structure; /* Yes, you need the & when dealing with 
                           structures and using pointers to them*/
    printf( "%d\n", ptr->x );  /* The -> acts somewhat like the * when 
                                   does when it is used with pointers
                                    It says, get whatever is at that memory
                                   address Not "get what that memory address


Unions are like structures except that all the variables share the same memory. When a union is declared the compiler allocates enough memory for the largest data-type in the union.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.