Structure in C can be defined as group of variables with same name and different data types which can be created, pointed to, copied, and refer to conveniently and easily. Unlike in C++, the names of structures are declared in a separate name space in C. .
#include<stdio.h> #include<conio.h> struct student { char name[20]; int age; float percentage; }file; int main() { strcpy(file.name, "John"); file.age=25; file.percentage=78-9; printf("Name is %s\n",file.name); printf("age is %d\n",file.age); printf("percentage is %f\n", file.percentage); }
Output:
Name is John age is 25 percentage is 69.000000
Structure Member
or an Element
.In the above example, John, age,percentage are called as tags which are of different data types.
Declaring will be same as defining.Coming to defining a structure, assign values to variables at the end of structure block( after the braces) by giving a semicolon.
struct student { char name[20]; int age; float percentage; } student1={"John",15,77.5}; student2{"Mike",16,78};
#include<stdio.h> #include<conio.h> #include"structure.h" int main() { strcpy(file.name, "splessons"); file.age=25; file.percentage=78-9; printf("Name is %s\n",file.name); printf("age is %d\n",file.age); printf("percentage is %f\n", file.percentage); }
#include <stdio.h> #include <string.h> struct student { int id; char name[30]; float percentage; }; int main() { int i; struct student record[2]; // 1st student's record record[0].id=1; strcpy(record[0].name, "John"); record[0].percentage = 86.5; // 2nd student's record record[1].id=2; strcpy(record[1].name, "Mike"); record[1].percentage = 90.5; // 3rd student's record record[2].id=3; strcpy(record[2].name, "Anderson"); record[2].percentage = 81.5; for(i=0; i<3; i++) { printf("Records of STUDENT : %d \n", i+1); printf("Id is: %d \n", record[i].id); printf("Name is: %s \n", record[i].name); printf("Percentage is: %f\n\n",record[i].percentage); } return 0; }
Output:
Records of STUDENT : 1 Id is: 1 Name is: John Percentage is: 86.500000 Records of STUDENT : 2 Id is: 2 Name is: Mike Percentage is: 90.500000 Records of STUDENT : 3 Id is: 3 Name is: Anderson Percentage is: 81.500000
The memory address given to a particular variable is called as a Pointer.
#include <stdio.h> #include <string.h> struct student { int id; char name[30]; float percentage; }; int main() { int i; struct student record1 = {1, "William", 90.5}; struct student *ptr; ptr = &record1; printf("Records of STUDENT1: \n"); printf(" Id is: %d \n", ptr->id); printf(" Name is: %s \n", ptr->name); printf(" Percentage is: %f \n\n", ptr->percentage); return 0; }
Output:
Records of STUDENT1: Id is: 1 Name is: William Percentage is: 90.500000