Structure is user defined data type which is used to store heterogeneous data under unique name. Keyword 'struct' is used to declare structure.
We already know that arrays are many variables of the same type grouped together under the same name.
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:
Code:
We already know that arrays are many variables of the same type grouped together under the same name.
Similarity with arrays
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 struct person
{ char *name;
int age;
};
Code:
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;
return 0;
} Code:
#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;
}
Comments
Post a Comment