Monday, 20 May 2019

C Data Types (Practice Question)

C | Data Types | Quiz Questions


Question 1

Predict the output of the following program
#include <stdio.h>
int main()
{
printf ("%d %o %x", 72, 72, 72);
return 0;
}

A. 72 110 48
B. 78 113 48
C. 70 110 48
D. 72 112 40

Explanation

Here, %d prints out as a decimal number, whereas %o prints octal equivalent of 72 and %x prints hexadecimal equivalent of 72.

Question 2

Find the output of the following program.
#include <stdio.h>
int main ()
{
printf ("%d %d%d %d", 61, 061, 0x61, 0X61);
return 0;
}

A. 72 32 118 113
B. 61 49 97 97
C. 70 58 114 114
D. 72 58 114 119

Explanation

The c programming language has three number systems decimal, octal and hexadecimal. To understand the difference between these numbers octal number is preceded by 0 and the hexadecimal number is preceded by 0x or 0X.

In the above code, 061, 0x61 and 0X61 using format specifier %d. The %d format specifier is used for the decimal number system. Therefore, decimal equivalents of octal 061, 0x61 and 0X61 get printed.

Question 3

What will be the output of the C program?
#include <stdio.h>
int main ()
{
void number = 11;
printf ("%v", number);
return 0;
}

A. 1
B. 0
C. Garbage value
D. Compilation error

Explanation

The void is not a valid data type for declaring variables.

Question 4

The format identifier "%i" is also used for which data type?
A. char
B. int
C. float
D. double

Explanation

"%i" format identifier is used for the int data type.

Question 5

In C, Size of an integer and a pointer must be same.
A. True
B. False

Explanation

The size of the pointer and integer depends on the compiler, it is not necessary that the size of the pointer is the same.

Question 6

Find the output of the following program?
#include <stdio.h>
int main()
{
float a = 0.5;
if (a==0.5)
printf("True");
else
printf ("False");
return 0;
}

A. True
B. False

Question 7

Find the output of the following C program
#include <stdio.h>
int main()
{
char b = '\012';
printf ("%d", b);
return 0;
}

A. Compiler error
B. 12
C. 10
D. Empty

Explanation

In, the octal value of 'b' is '\012' but in decimal '10'.
Note
int a ='\012'
int a = 012
All are equal.

Question 8

Assume that the size of char is 1 byte and negative are stored in 2's complement form,
#include <stdio.h>
int main()
{
char d = 125;
d = d+10;
printf ("%d", d);
return 0;
}

A. 135
B. INF
C. -121
D. -8

Explanation

125 is represented as 01111101 in binary and we add 10 i.e. 1010 in binary it becomes 10000111. Now, what does this number represent: Firstly, you should know that char can store numbers only -128 to 127 since the most significant bit is kept for the sign bit. Therefore, 10000111 represents a negative number. To check which number it represents we find the 2's complement of it and get 01111001 which is 121 in the decimal system. Hence, the number 10000111 represents -121.

Question 9

Predict the output of the following program
#include <stdio.h>
int main( )
{
if (sizeof(int)>-1)
printf ("YES");
else
printf("NO");
return 0;
}

A. YES
B. NO
C. Compiler error
D. Runtime error

Explanation

In C, when the integer value is compared with an unsigned one, the integer is encouraged to unsigned. Negative numbers are stored in the form of 2's complement and the unsigned value of the 2's complement form is more than the size of the integer. 

Question 10

Which data type is most suitable for storing a number 65000 in a 32-bit system?
A. signed short
B. unsigned short 
C. long
D. int

Explanation

The range of short (16-bit) is 0 to 65536. So, 65000 comes in the range from 0 to 65536. That's why unsigned short is the correct answer.

Question 11

Which of the following is a user-defined data type?
A. Function
B. Pointer
C. Structure
D. All of the above

Question 12

What is the output of the following code?
#include <stdio.h>
int main()
{
signed char ch;
ch=128;
printf ("%d\n", ch);
return 0;
}

A. 128
B. -128
C. Depends on the compiler
D. None of the mentioned

Explanation

The range of the signed character between -128 to 127.

C Data types











The positive value is from 0 to 127, 127 numbers have been counted, now what comes next after 127 is 128 but if you see it in the circle, then what number has come after 127 i.e. -128.

Question 13

What is short int the C programming?
A. The basic data type of C
B. Qualifier
C. Short is the qualifier and int is the basic data type
D. All of the above

Question 14

Which of the following is not a valid declaration in C?
1. signed short a;
2. short a;
3. short int a;
4. unsigned short a;

A. 3 and 4
B. 2
C. 1
D. All are valid

Question 15

What will be the output when you will execute the following C code?
#include <stdio.h>
int main()
{
printf ("%d\n", sizeof(4.5));
printf ("%d\n", sizeof(80000));
printf ("%d\n", sizeof ('B'));
return 0;
}

A. 4 2 1
B. 8 2 1
C. 4 4 1
D. 8 4 2

Explanation

The size of data types in the C programming language depends on the compiler. 
In the code block, 4.5 is a double data type.
80000: int
'B': Char
Double is of 8 bytes.
Character is of 4 bytes.
int is 4 bytes.






Recommended Post
Data types in C
Pointers in C










Friday, 10 May 2019

Learn Data Types in C

The data types in C tells the compiler or interpreter what type of data a programmer is using and how many memory (bytes) a variable is needed. How much memory a variable is needed is predefined. Data types are Primary data types and Derived data types.

Data types in C

















Pre-define Data Types or Fundamental Data Types in C

This data type was defined by C standard and these data types are int (integer), float (floating), char (character), double etc. With the help of the sizeof operator, we can know the size of data types in C. These data types are the platform dependent so, C standard also introduces the fixed size of data type like uint8_t, uint16_t etc. Pre-define data types are defined in <stdint.h> header file. These data types are also known as primary data types in C.

int

int is a whole number, it keeps both zero, negative and positive numbers, it does not contain any decimal value.
Syntax
int name_of_variable;

Size of an integer is 4 bytes for the 32-bit compiler.


float

It stores decimal values with single accuracy. Float is used to hold real numbers. Floating point numbers can also be represented exponentially (Example: 25.936e5).
Syntax
float price_of_product;

char

This data type is used to define the character variable and it needs one byte of memory. 
Syntax
char name_of_character;
char a = 'c';

double

It stores decimal values with double accuracy. Double is also used to hold real numbers. 
Syntax
double salary;

Signed and unsigned 

Signed and unsigned are type modifiers. With the help of these modifiers, we can change the data storage of a data type. For example,
int a;
unsigned int b;

Here, the variable 'a' can hold positive and negative values, and its range is from -2^31 to 2^31-1. Whereas variable 'b' can hold zero and positive values, and its range is from 0 to 2^32-1.


Each data types has its own range of how many numbers or values it can store. These ranges vary from compiler to compiler (like 32-bit compiler have different range and 64-bit compiler have the different range).

Data types in C



























Below a program has been written using the sizeof operator, with the help of sizeof operator you can learn how to find out the size of different data types in C.

#include <stdio.h>
int main( )
{
    int number = 20;
    char alphabet = 'A';
    float d = 8.6;
    double c = 7.22;
    printf ("Welcome\n");

//Printing the value and size of an integer data type.
printf ("Welcome, I am an integer. My value is %d and size is %lu bytes.\n", number, sizeof (number));

//Printing the value and size of a character data type.
printf ("Welcome, I am a character. My value is %c and size is %lu bytes.\n", alphabet, sizeof (alphabet));

//Printing the value and size of float data types in C
printf ("Welcome, I am float. My value is %f and size is %lu bytes. \n",d,sizeof (d));

//Printing the value and size of double data types in C
printf ("Welcome, I am double. My value is %lf and size is %lu bytes. \n", c, sizeof (c));

printf ("Goodbye");
return 0;
}

Output
Welcome
Welcome, I am an integer. My value is 20 and size is 4 bytes.
Welcome, I am a character. My value is A and size is 1 byte.
Welcome, I am float. My value is 8.600000 and size is 4 bytes.
Welcome, I am double. My value is 7.220000 and size is 8 bytes.
Goodbye

User-define data types in C

C language allows programmers to create their own data type. A user-defined data type is created by the user by using the keyword struct (Structure in C), union (Union in C), array (Array in C), strings (Strings in C), Function, pointer, enum etc. 























































Monday, 29 April 2019

What are Tokens in C? (Learn with Video)

A token in C is a character, word or something that a programmer uses to create a program. It's like bricks, cement, sand and other things that will be used to make the structure. Similarly, tokens in C are their own predefined types or functions in the compilation that make syntax for a program.




Whenever we are talking about the English language, punctuation, conjunction and words are tokens in that language.  Tokens in C are the very small unit and it is very important to the compiler. Basically, tokens in C are the building blocks in the programming language.

Program
int main ( )

{
int a=10b=20sum;
sum=a+b;
printf ("sum=%d"sum);
return 0;
}

 Tokens in the C (the above) program are mention below. 

main - identifiers
{ }, ( ) - special symbols
int - keywords
a, b, sum - identifiers
10, 20 - constant
=   assignment Operator
+   addition operator



tokens in C
Types of tokens in C


CATEGORIZATION OF TOKENS IN C

  1. Constant

  •  Constant whose value is fixed, we cannot change their value throughout the program. 
  • Constant is also known as literals.

Types of Constant


1.1 Integer Constant

An integer constant is a whole number, it should have at least one number and this number can be a positive (+) or negative (-) number.

Integer Constant are decimal, octal and hexadecimal. 

An octal integer constant (0): 0 is added before a number like 022 (it means given or mention number is octal). The octal number lies from 0 to 7. For example, 123 is octal value and 9AB is not an octal value.
Hexadecimal integer constant (0x or 0X): 0x or 0X is added before a number like 0x345 or 0X345 (it means given number is hexadecimal) shows that particular number is hexadecimal. Hexadecimal values are lies from 0 to 16 (0,1,2,3,4,5,6,7,8,9, A(10), B(11), C(12), D(13), E(14), F(15). For example, 0xD, 0XA.
A decimal integer constant: Decimal values lies from 0 to 9. These values may be positive or negative. 223 is a decimal number or -34 is also a decimal value.

Note: Space, commas and special characters are not permitted between digits.

1.2 Float Constant

Float Constant are also known as real constant. Decimal values in mathematics are called float constant in the C programming language. For example 17.4456, -89.67, 0.65e4.

1.3 Character Constant

  • The single character constant is enclosed in single quotes like 'A', 'c' or '5'.
          '5' and 5 both are different.
  • printf ("%c", a);
         This statement will print the character 'a'.
  • printf ("%d", a);
          This statement will print the value of character 'a' that is 97.

1.4 String Constant

  • A string is an array of character and always ended with a null character ['\0'].
  • A string constant is enclosed in double quotes. 
  • "Hello World" is a string constant
  • It can contain any special characters, space, numbers etc. like "Welcome 98", "123457654", "123%^$@#".

2. Keywords

  • Keywords are reserved words in the C programming language. We cannot use as variable, constant or string. It has a special/unique meaning for the compiler. 
  • 32 keywords are defined and we can not redefine these keywords in our C programming language. If we are trying to use these 32 keywords as a variable name or in any other manner in the C program then compiler produces an error. 

Tokens in C
Keywords 

3. Identifiers

  • Identifiers consist of alphanumeric characters (A-Z), underscore, digits. Identifiers first character can be a letter or underscore ( _ ). Special characters are not used in c as identifiers. For example, _B6 is a valid identifier, void/main are keywords so, we can't use as an identifier, Var.b  is also not used as an identifier.
  • Identifiers are case sensitive. We cannot use keywords as identifiers.

For example
#include <stdio.h>
int main ( )
{
int RollNo=10;
char Name_of_Student[ ] = "ABCDE";
float marks =12.5;
int arr[5]={1,2,3,4,5};
char row = A';
printf ("%d\n%s\n%f\n%c\n", RollNo, Name_of_Student, marks, row);
//Note: RollNo,  Name_of_Student, marks, arr, row are identifiers.
return 0;
}

4. Operator

An operator is a symbol which tells the compiler that which type of operation has to be performed.

Types of operator

  1.   Arithmetic operator
  2.   Logical operator
  3.   Relational operator
  4.   Bitwise operator
  5.   Unary operator
  6.   Conditional operator
  7.   Assignment operator

For example
output = a + b;
= Assignment operator
+ Addition operator (Arithmetic operator)
a and b are operands

To read the article on OPERATOR IN C

5. Special symbols

They have some special meaning in the C programming language for the compiler and it is used to perform some special function/task in C.

5.1. Brackets

5.1.1 Square brackets [ ]: It is used to define the size of an array, string etc. For example, int arr[5];

The integer data type is of 4 bytes and arr[5] means array arr contain 5 integer data. How many bytes arr [5] occupy is 5*4=20 bytes. 20 bytes are allocating in memory.

5.1.2 Curly brackets { }: These brackets are used to define the scope of the block.
          {   <====  Opening brackets

           } <====   Closing brackets

Statement/code/argument is written in between the opening and closing brackets.

 For example
 #include <stdio.h>
int main( )
 {                    // Opening bracket
 printf ("Welcome to My blog");           // statement
  return 0;
                // Closing bracket

 5.1.3 Round brackets ( ): These brackets are used to defined function like main ( ), for ( ), strcpy ( ), strlen ( ) etc. and function parameters are written inside these brackets. 
For example  for (i=0; i<10; i++)


5.2 A semicolon (;): In the English language, we use a full stop (.) to terminate from the statement/line. Similarly, a semicolon is used to terminate from statements in the C programming language. This symbol tells to the compiler, it is the end of the statement and moves to the next statement. 


5.3 The comma (,): Comma is used to separate more than one statement. It is not used for the termination of the statement. Comma separate more than one statement like separating parameters in the function call.


For example: 
int a=20, b=30, c,i;
add (a,b);


5.4 The assignment operator (=):  This operator is used to transfer the data from one variable to another variable. For example: 
g =17;
The value 17 is transfer to value g.
or 
int k = 20;
g = k;

The value of k i.e. 20 is transferred to g with the help of the assignment operator.

5.5 Asterisk (*):  This symbol is used for multiplication and to create a pointer variable.




Monday, 22 April 2019

Do While Loop in C

While loop and do while loop in C is similar, the basic difference is that the test-condition in the while loop checks on the initial stage whereas in the do-while loop, the test-condition is defined at the bottom due to which the do-while loop runs at least once.


Do-while loop in C

Syntax of the do while loop in C

do
{
Body statements;
} while (test_condition);



Flow Diagram of do while loop in C

do while loop in C
Flow diagram of do while loop in C

Without checking test condition, the loop is executed at least once, after that test condition inside the while loop is evaluated, if it is true then loop body will execute otherwise. Let's try to understand this concept with the help of the program,

A Program which prints the value from 1 to 5.

#include <stdio.h>
int main( )
{
    int i=0;
    do
    {
      i++;
      printf ("output %d\n",i);
    }while(i<5);
    return 0;
}

Output
Output 1
Output 2
Output 3
Output 4
Output 5

Explanation
In the above program, the variable 'i' is initiated to 0. Now, the loop body is executed at least once. Variable 'i' is incremented to 1, after that output is printed. Now, test-condition (i<5) is evaluated, if this condition is true then output is occurring otherwise.

Do while loop without body

#include <stdio.h>
int main ( )
{
    int i=0;
    printf ("Hello World");
    do
    {

    }while(i<5);
    return 0;
}

Output
Hello World

Infinite do while loop in C

Example 1
#include <stdio.h>
int main( )
{
do
{
printf ("Infinite do while loop in C");
}while(1);
return 0;
}

Output
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
:
:
:
:
:
up to infinity

Example 2
#include <stdio.h>
int main ( )
{
    do
    {
        printf ("Infinite do while loop in C\n");
    }while(11>1);
    return 0;
}

Output
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
.
.
.
.
.
.
.
.
.
.
.
.
up to infinity

Example 3
#include <stdio.h>
int main ( )
{
    int i=10;
    do
    {
        i--;
        printf ("Infinite do while loop in C\n");
    }while (i<11);
    return 0;
}

Output
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
Infinite do while loop in C
.
..
.
..
.
.
up to infinity













Monday, 15 April 2019

While loop in C

In the for loop, we know how many times a loop will execute. While we did not know how many times a while loop will be executed. Execution of while loop is based on the test condition. 

While loop in C

The syntax of While loop in C

While loop will be executed until the test condition is failed.

while (test_condition)
{
body statements;
update expressions;
}



Flow Diagram of while loop in C


while loop in C

First, the test condition inside the parenthesis is evaluated. If the test condition is true then while loop body is executed until the test condition fails.

The test condition may be any value (true or non-zero) or any expression.

A program which prints the value from 1 to 10.

#include <stdio.h>
int main( )
{
    int value = 1; //Initialize value
    while (value <= 10) //Test condition
    {
        printf("value is %d\n",value);
        value++; //increment value
    }
    return 0;
}

Output
value is 1
value is 2
value is 3
value is 4
value is 5
value is 6
value is 7
value is 8
value is 9
value is 10

Explanation
In the above program variable 'value' is set to '1'. Execution of while loop is started. If the test condition is true then the statements inside the loop body will execute i.e. print statement and post-increment statement. This loop will execute until the test condition (value<=10) fails. 

While loop in C with no body

#include <stdio.h>
void main( )
{
    int a=1,b=11;
    printf ("%d\n",a);
    printf ("%d\n",b);
    while(a<b);
}

Output
1
11

Infinite while loop in C

Example 1
#include <stdio.h>
int main( )
{
    while(1)
        printf("Infinite While Loop in C");
    return 0;
}

Output
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
.
.
.
.
.
.
.
Up to infinite 

Example 2
#include <stdio.h>
int main( )
{
    while(11>1)
        printf ("Infinite while loop in C\n ");
    return 0;
}

Output
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
.
.
.
.
.
.
.
Up to infinite 

Example 3
#include <stdio.h>
int main( )
{
    int a = 10;
    while(a<=20)
    {
        printf ("Infinite While Loop in C\n");
        a--;
    }
    return 0;
}

Output
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
Infinite While Loop in C
.
.
.
.
.
.
.
Up to infinite 

C program to print the table of 3.

#include <stdio.h>
int main ( )
{
    int a = 3,i=1;
    while (i<=10)
    {
        printf ("%d\n",a*i);
        i++;
    }
    return 0;
}


Output
3
6
9
12
15
18
21
24
27
30

Use of Logical Operators in While loop in C

Like relational operators, logical operators can also use in the while loop in C

Using AND Operator 

while ( a > 10 && b 10)
The loop body will execute when both conditions are true.

Using OR Operator

while (<=10 || <=11)
The loop body will execute if the anyone test condition is true.

Using NOT Operator

while (!= b)
The loop body will execute if the variable 'a' is does not equal to 'b'.

Program for while loop using logical operator in C

#include <stdio.h>
int main ( )
{
    int a = 10, b = 30, c = 4;
    while((a > 6 || b < 35 && c)!=a)
    {
        printf ("Loop Body Executed\n");
        a--;
        b++;
        c--;
    }
}


Output
Loop Body Executed
Loop Body Executed
Loop Body Executed
Loop Body Executed
Loop Body Executed
Loop Body Executed
Loop Body Executed
Loop Body Executed
Loop Body Executed
Loop Body Executed

What will happen when the test condition in the while loop has zero value?


#include <stdio.h>
int main ( )
{
    while(0) //Zero value is considered as false value, so the loop body will not execute.
    {
        printf ("Loop will executed\n");
    }
    printf ("Loop will not be executed\n");
    return 0;
}


Output
Loop will not be executed






Monday, 8 April 2019

Dynamic Memory Allocation in C Using Malloc(), Calloc(), Free(), Realloc()


Dynamic memory allocation in C



















To understand the concept of dynamic memory allocation in C, first, we need to understand why we need it? Whether we talk about the C programming language or some other programming language, there are some rules for every programming language. C is a structured programming language and it has some fixed rules. Let's try to understand that need and concept of dynamic memory allocation in C with the help of array.



Declaration of an array in C

int employees [100];

An int is of 4 bytes, 100*4 = 400 bytes are reserved in memory. If you want to store details of 70 employees, you can do it but 30 memory locations will be wasted and if you want to store details of 120 employees, you can store detail of 100 employees, but details of 20 employees are not saved. Are you thinking that why this is happening? This is happening because we have used the concept of static memory here if we want that memory should be allocated at the time of execution of the program. So, Dynamic memory allocation concept meets our needs. Let's try to understand this concept. 

What is Dynamic Memory Allocation in C?

Dynamic memory allocation in C helps us to allocate memory during runtime of the program. The dynamic memory allocation is done by using the standard library function <stdlib.h>. This library function consist of malloc (), calloc(), free() and realloc() function in C.



1. malloc ( )

"malloc" or memory function allocates a block of memory of specified size. It returns a void pointer which can be used in a pointer of any form. 

Syntax
pointer_variable = (cast-type*)malloc(Size_in_bytes);

For example
pointer_variable = (int*)malloc(30*sizeof(int));


We know that the size of the integer data types in C is of 4 bytes, the above statement allocates 120 bytes of memory and pointer_variable holds the address of the first byte of the memory block. 

Dynamic memory allocation in c












If 40 bytes are not available in memory that means insufficient space then memory allocation fails and it returns a null pointer

Dynamic memory allocation in C using malloc ( ) function
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *pointer; // This pointer will hold the address of first byte of allocated block of memory.
    int num, i, total = 0;
    //Number of elements in an array.
    num = 4;
    printf ("Enter number of elements in an array:%d\n",num);
    //Allocate memory using malloc () function
    pointer = (int*)malloc(num*sizeof(int));
    //Check memory is successfully allocated by malloc () function
    if(pointer == NULL)
    {
        printf("Memory not allocated\n");
    }
    else
    {
        printf("Memory is allocated using malloc function\n");
        //Elements of an array
        for (i=0;i<num;i++)
        {
            pointer[i]=i+1;
        }
        printf("Elements of an array\n");
        for(i=0;i<num;i++)
        {
            printf("%d\n",pointer[i]);
        }
    }
    return 0;
}

Output
Enter the number of elements in an array:4
Memory is allocated using malloc function
Elements of an array
1
2
3
4

2. calloc ( )

"calloc" or contiguous allocation is used to allocate the block of memory during runtime of the program of the specified size. Every block of memory is initialized with default value zero.

Syntax
pointer_variable = (cast-type*)calloc(number_of_elements, Size_in_bytes);

For example
pointer_variable=(int*) calloc(10, sizeof(int));

The above statement contiguously allocates 40 bytes of memory for 10 elements and each element is of 4 bytes.

Dynamic memory allocation in C












Dynamic memory allocation in C using calloc ( ) function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *pointer; //This pointer will hold the address of first byte of allocated block of memory.
    int num, i, total = 0;
    num = 4; //Number of elements in an array
    //Dynamic memory allocation in C using calloc function
    pointer = (int*)calloc(num,sizeof(int));
    if (pointer==NULL)
    {
        printf("Memory space is insufficient\n");
    }
    else
    {
        printf("Memory is allocated\n");
        for(i=0;i<num;i++)
        {
            pointer[i]=i+2;
        }
        //An array elements
        for(i=0;i<num;i++)
        {
            printf("%d\n",pointer[i]);
        }
    }
    return 0;
}


Output
Memory is allocated
2
3
4
5

3. free ( )

This function is used to de-allocate memory. Calloc ( ) and malloc ( ) function does not de-allocate memory by themselves. So, the free ( ) function is used, it reduces the wastage of memory.

Syntax
free (pointer);

Dynamic memory allocation in C





















Free allocated memory using the free ( ) function.

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *pointer; //This pointer will hold the address of first byte of allocated block of memory.
    int num, i, total = 0;
    num = 4; //Number of elements in an array
    //Dynamic memory allocation in C using calloc function
    pointer = (int*)calloc(num,sizeof(int));
    if (pointer==NULL)
    {
        printf("Memory space is insufficient\n");
    }
    else
    {
        printf("Memory is allocated\n");
    }
    free(pointer);
    printf("Memory is freed");
    return 0;
}


Output
Memory is allocated
Memory is freed

4. realloc ( ) 

"realloc" or re-allocation function is used to change the allocated memory. If the memory allocated by calloc and malloc function is insufficient then the realloc function is used to re-allocate memory dynamically.

Syntax
pointer_variable= realloc(pointer_variable, new_size);

Dynamic memory allocation in C





















Re-allocate memory using realloc () function
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *pointer; //This pointer will hold the address of first byte of allocated block of memory.
    int num, i, total = 0;
    num = 4; //Number of elements in an array
    //Dynamic memory allocation in C using calloc function
    pointer = (int*)calloc(num,sizeof(int));
    if (pointer==NULL)
    {
        printf("Memory space is insufficient\n");
    }
    else
    {
        printf("Memory is allocated\n");
        for(i=0;i<num;i++)
        {
            pointer[i]=i+2;
        }
        //An array elements
        for(i=0;i<num;i++)
        {
            printf("%d\n",pointer[i]);
        }
    }
    //Change the size of new array
    int new_num=10;
    //Re-allocate memory using realloc() function
    pointer=realloc(pointer,new_num*sizeof(int));
    for(i=5;i<new_num;++i)
    {
        pointer[i]=i+2;
    }
    //Print the elements of the array
    for(i=0;i<new_num;++i)
    {
        printf("%d\n",pointer[i]);
    }
    free(pointer);
    return 0;
}


Output
Elements in an array
2
3
4
5
New Elements in an array
2
3
4
5
5
6
7
8
9
10

Difference between static memory allocation and dynamic memory allocation in C

1. In static memory allocation, memory is allocated at compiling time and dynamic memory is allocated at executing time of the program.
2. In static memory allocation, memory size can't be changed during execution of the program, it's size is fixed but in dynamic memory allocation, size of memory can be changed during execution of the program.

Difference between malloc ( ) and calloc ( ) funtion in C


Dynamic memory allocation in C