how to define structure in c code example
Example 1: 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 2: C structure
struct struct1 {
int a;
char b;
}
typedef struct struct2 {
int a;
char b;
} name;
void main()
{
struct struct1 var1;
name var2;
var1.a = 10;
var2.b = 'c';
}
Example 3: Structure of Structs in c
The basic structure
Example 4: Structure of Structs in c
struct [structure_tag]
{
//member variable 1
//member variable 2
//member variable 3
...
}[structure_variables];