structure declaration in c code example
Example 1: structure and function in c
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student *record);
int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(&record);
return 0;
}
void func(struct student *record)
{
printf(" Id is: %d \n", record->id);
printf(" Name is: %s \n", record->name);
printf(" Percentage is: %f \n", record->percentage);
}
Example 2: structs in c
#include <stdio.h>
#include <stdlib.h>
struct book{ //this is like making a datatype of type book
//these are the fields
char name[50];
char author[50];
char ISBN[11];
};
int main(){
struct book book1; //making an instance of book called book1
/*
normally to store integers in a struct we can do something like
book1.number_of_pages = 22; which is correct
however with character arrays we need to use the strcpy
function
*/
strcpy(book1.name, "james and the giant tatti");
strcpy(book1.author, "Krishan Grewal");
strcpy(book1.ISBN, "12345678987");
printf("book name: %s\n", book1.name);
printf("book author: %s\n", book1.author);
printf("book ISBN: %s\n", book1.ISBN);
return 0;
}
Example 3: declare structure in c
struct num{
int a ;
int b;
};
int main()
{
struct num n;
//accessing the elements inside struct
n.a=10;
n.b=20;
}
Example 4: structure and function in c
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
struct student record; // Global declaration of structure
void structure_demo();
int main()
{
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
structure_demo();
return 0;
}
void structure_demo()
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}