->Watch this for FUN - Funny job interview
Are you getting bored with online lectures?
->Watch this - When online lectures are boring
Structures in C is a very important topic in the C programming language as it can store multiple data types due to which it comes under the user-defined data type.
By the multiple data types, I mean that it can store data types like int, float, char, double, etc.
The declaration of a structure in C goes like:
struct name{ // name is Name of the structure
int n,m; //int data type
float f; //float data type
char a[20000]; //character data type
};
NOTE:- You cannot initialize any data type in structures, like
struct name{
int n=3,m=2; // ERROR
float f=3.5; //ERROR
};
By using structures, it would become very easy to store multiple information of any kind.
For using structures in the int main in C, let's take the example of storing the ID, NAME of the student, the program goes like,
#include<stdio.h>
#include<string.h>
struct student{
int ID;
char NAME[100000];
};
int main()
{
int n; //For the number of students
scanf("%d",&n);
struct student s[n];
int i;
for(i=0;i<n;i++)
{
scanf("%d\n",&s[i].ID); // For storing the ID, We used \n for removing the buffer.
gets(s[i].NAME);
}
for(i=0;i<n;i++)
{
printf("%d\n",s[i].ID); // For printing the ID
puts(s[i].NAME);
}
}
<><><><><><><>
Pointers in Structures in C:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct student{
int *ID;
char *NAME;
};
int main()
{
int n; //For the number of students
scanf("%d",&n);
struct student s[n];
int i;
for(i=0;i<n;i++)
{
scanf("%d\n",&s[i].ID); // For storing the ID, We used \n for removing the buffer.
s[i].NAME=(char *)malloc(10000);
gets(s[i].NAME);
}
for(i=0;i<n;i++)
{
printf("%d\n",s[i].ID); // For printing the ID
puts(s[i].NAME);
}
}
<><><><><><><>
Pointers to a structure in C:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct student{
int ID;
char NAME[10000];
};
int main()
{
struct student *s,g; // for allocating memory to a pointer in a structure it should be defined with a structure too!!
s=&g; // For pointers to a structure we uses -> to point to a data type
int i;
scanf("%d\n",&s->ID); // For storing the ID, We used \n for removing the buffer.
gets(s->NAME);
printf("%d\n",s->ID); // For printing the ID
puts(s->NAME);
}
Are you getting bored with online lectures?
Watch this - When online lectures are boring
Watch this for FUN - Funny job interview
<><><><><><><>
<><><><><><><>
Comments
Post a Comment