Programs to understand Structures.
Structure : Structure is a group of variables of different data types represented by a single name.Each element of a structure is called a member.
Syntax :
struct structureName { dataType member1; dataType member2; ... data_type memeberN; }; |
---|
Example : memory allocation of the structure ABC is 4 + 20 + 4 =28 bytes i.e size of int =10 byte , size of char is 1 byte so 1*20 =20 byte and size of float is 4 bytes .
struct ABC { int id; char n[20]; float s; }; |
---|
How we create structure variables:
Example-1 :
struct ABC { char n[50]; int c.No; float s; }; int main() { struct ABC a1, a2, a[20]; return 0; } |
---|
Example :
struct ABC { char n[50]; int c.No; float s; }a1, a2, a[20]; |
---|
How to access members of a structure
Two types of operators used for accessing members of a structure.
- "."(Dot) - Member operator
- "-> " - Structure pointer operator (done using pointers)
Example :
#include<stdio.h> #include <string.h> struct employee { int id; char name[50]; }e1; //declaring e1 variable for structure int main( ) { //store first employee information e1.id=111; //copying string into char array strcpy(e1.name, "Aman singh"); //printing first employee information printf( "employee 1 id : %d\n", e1.id); printf( "employee 1 name : %s\n", e1.name); return 0; } |
---|
Output :
employee 1 id : 111
employee 1 name : Aman singh
Example-2 :
#include<stdio.h> #include<conio.h> struct Point { int x, y; }; int main() { struct Point p1 = {1, 2}; // p2 is a pointer to structure p1 struct Point *p2 = &p1; // Accessing structure members using structure pointer printf("%d %d", p2->x, p2->y); return 0; } |
---|
Output : 1 2
Limitation of Structures :
- C Structures do not permit data hiding. Structure members can be accessed by any function, anywhere in the scope of the Structure.
- Structures do not permit functions inside Structure
- Structures cannot have static members inside their body
- C Programming language do not support access modifiers. So they cannot be used in C Structures.
- Structures in C cannot have constructor inside Structures.
For more RTU/BTU II Sem Computer Programming Lab Experiments CLICK HERE