User defined datatype - Structure

In the C language structures are used to group together different types of variables under the same name. For example you could create a structure “telephone”: which is made up of a string (that is used to hold the name of the person) and an integer (that is used to hold the telephone number).
Take a look at the example:

 struct telephone
 {
  char *name;
  int number;
 };

Note: the ; behind the last curly bracket.
With the declaration of the structure you have created a new type, called telephone. Before you can use the type telephone you have to create a variable of the type telephone. Take a look at the following example:

 #include<stdio.h>

 struct telephone
 {
  char *name;
  int number;
 };

 int main()
 {
  struct telephone index;

  return 0;
 }

Note: index is now a variable of the type telephone.
To access the members of the structure telephone, you must use a dot between the structure name and the variable name(variables:name or number.) Take a look at the next example:

 #include<stdio.h>

 struct telephone
 {
  char *name;
  int number;
 };

 int main()
 {
  struct telephone index;

  index.name = "Jane Doe";
  index.number = 12345;
  printf("Name: %s\n", index.name);
  printf("Telephone number: %d\n", index.number);

  return 0;
 }




Spread the word! By sharing this Post!

Pageviews This Week