Struct
Struct is a data type that can perform multiple data storage interlinked (such as name, id number, age) as a whole. Struct consists of several members, members of the struct called members, and members can also be called a regular variable. Members in a structure may consist of different data types, such as pointers, integer, character, and others. Here is an example of structure.
the general form:
struct Tag {
Member1;
Member2;
Member3;
};
Example:
struct Student{
char name[10];
int id_number;
int age;
};
The right time to use Struct is when we need to create a new data type that can store multiple variable. like the example in Student struct can contain multiple variable that is character and integer.
A pointer is an address that contains the data object to memory location in which a stored value.
Variable - variable pointer variable declaration is declared as usual, just added the sign ( * ) behind variable name.
the general shape of the pointer is :
The type of data * variable name ;
Where the data type is the type of data stored at the address designated by variable_name.
Example:
Int * pointer ;
Float * pointer ;
The first * pointer is a pointer to an integer data type and second *pointer is a pointer to float data type.
The value of the pointer variables can be declared at the same time.
the first value is the address in the memory location.
The right time to use pointer is when we need to change a variable content on another's function.
Example :
int point(int *x) {
*x = 5;
}
int main() {
int y = 0;
point(&y);
printf("%d\n", y);
}
in this program the first value of y = 0 is change to 14 because of the pointer.
Function
function is several statements which together perform a task. every program even most simple program has at least one function. So we always need function.
Example:
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main () {
/* local variable definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
printf( "Max value is : %d\n", ret );
return 0;
}
The right time to use function is when we have the same loop and the loop used repeatedly so we just write it once.
Array
Array is used to store variables with the same data type. array can simplify the code.
The right time to use array when the number of inputs to be stored are too many and when we want to simplify the loop.
font-family: "times" , "times new roman" , serif; font-size: large;">
font-family: "times" , "times new roman" , serif; font-size: large;">Example That Uses Combination Of Struct, Pointer/reference, Function, Array
#include <stdio.h>
int main(){
struct student{ // this is struct
char name[10]; // this is array inside struct
int id;
int marks;
}
stud1 = {"Manchunian
struct student *ptr;
ptr = &stud1; // this is pointer to struct
printf("Name :%s\n",(ptr)->name);
printf("ID: %d\n",(ptr)->id);
printf("Marks of Student : %d\n",(ptr)->marks);
return 0;
}