Like us on Facebook to get the latest links daily

Friday, January 27, 2012

Structures in C





We already know that arrays are many variables of the same type grouped together under the same name. Structures are like arrays except that they allow many variables of different types grouped together under the same name. For example you can create a structure called person which is made up of a string for the name and an integer for the age. Here is how you would create that person structure in C:
struct person
{
   char *name;
   int age;
};

The above is just a declaration of a type. You must still create a variable of that type to be able to use it. Here is how you create a variable called p of the type person:
#include<stdio.h>
 
struct person
{
   char *name;
   int age;
};
 
int main()
{
   struct person p;
   return 0;
}

To access the string or integer of the structure you must use a dot between the structure name and the variable name.
#include<stdio.h>
 
struct person
{
   char *name;
   int age;
}/;
 
int main()
{
   struct person p;
   p.name = "John Smith";
   p.age = 25;
   printf("%s",p.name);
   printf("%d",p.age);
   return 0;
}/

Type definitions

You can give your own name to a variable using a type definition. Here is an example of how to create a type definition called intptr for a pointer to an integer.
#include<stdio.h>
 
typedef int *intptr;
 
int main()
{
   intptr ip;
   return 0;
}/

Type definitions for a structure

If you don't like to use the word struct when declaring a structure variable then you can create a type definition for the structure. The name of the type definition of a structure is usually all in uppercase letters.
#include<stdio.h>
 
typedef struct person
{
   char *name;
   int age;
} PERSON;
 
int main()
{
   PERSON p;
   p.name = "John Smith";
   p.age = 25;
   printf("%s",p.name);
   printf("%d",p.age);
   return 0;
}

Pointers to structures

When you use a pointer to a structure you must use -> instead of a dot.
#include<stdio.h>
 
typedef struct person
{
   char *name;
   int age;
} PERSON;
 
int main()
{
   PERSON p;
   PERSON *pptr;
   PERSON pptr = &p;
   pptr->name = "John Smith";
   pptr->age = 25;
   printf("%s",pptr->name);
   printf("%d",pptr->age);
   return 0;
}/ 


Get E-mail Subscription for Latest Updates


Don't forget to Click on activation link , sent to your E-mail ID

No comments:

Post a Comment

You might also like:

Related Posts Plugin for WordPress, Blogger...