Programming C – Shishir Kant Singh https://shishirkant.com Jada Sir जाड़ा सर :) Mon, 04 Sep 2023 17:19:49 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://shishirkant.com/wp-content/uploads/2020/05/cropped-shishir-32x32.jpg Programming C – Shishir Kant Singh https://shishirkant.com 32 32 187312365 Function Pointer in C Programming https://shishirkant.com/function-pointer-in-c-programming/?utm_source=rss&utm_medium=rss&utm_campaign=function-pointer-in-c-programming Mon, 04 Sep 2023 17:19:45 +0000 https://shishirkant.com/?p=4301 Function Pointer in C Language

The pointer variable which holds the address of a function is called a function pointer. The basic advantage of a function pointer is that 1 function can be passed as a parameter to another function. Function pointer calls are faster than normal functions.

We already discussed that, in C Programming Language, we can create a pointer of any data type such as int, char, float, etc. It is also possible in C Programming Language that, we can create a pointer pointing to a function. In that case, the code of that function always resides in the memory. That means the function now has some address. We can get the address of memory by using the function pointer.

Example: Function Pointer in C Language

Let us understand Function Pointer in C Language with an example. In the below sample code, we are simply printing the address of the main and Fun functions.

#include <stdio.h>
int Fun()
{
    int x = 10;
}
int main ()
{
    printf ("Address of Main Function : %p", main);
    printf ("\nAddress of Fun Function : %p", Fun);
    return 0;
}
Output: 
Function Pointer in C Language

From the above output, we can observe that the main() function as well as any other functions have some addresses. Therefore, we can also conclude that every function has some address.

Declaration of a Function Pointer in C Language:

In the previous example, we conclude that every function has some addresses. So, now, we will see how to create a pointer and how a pointer points to those function addresses.

Syntax of Function Pointer in C Language:
return_type (*ptr_name)(type1, type2…);

Example1: int (*IP) (int);
In this example, *IP is a pointer that points to a function that returns an integer value and accepts an integer value as an argument.

Example1: float (*FP) (float);
In this example, *FP is a pointer that points to a function that returns a float value and accepts a float value as an argument.

So, here, you can observe that the declaration of a function pointer is similar to the declaration of a function except that the pointer is preceded by a ‘*’. So, in the above two examples, FP and IP are declared as functions rather than pointers.

As of now, we have seen only how to declare a function pointer in C Language. Now. we will see how to assign the address of a function to a function pointer in C Programming Language.

How to assign the address of a function to a function pointer in C?

Let us see, how to assign the address of a function to a function pointer in C Language. The most important point that you need to remember is that the declaration of a function is necessary before assigning the address of that function to a function pointer. The following three statements describe the declaration of a function, declaration of a function pointer, and assigning the address of the function to a function pointer
Declaration of Function: int fun(int , int);
Declaration of a Function Pointer: int (*IP) (int , int);
Assigning the address of fun to the IP pointer: IP = fun;
In the above declarations, the function pointer IP contains the address of the fun function.

How to Call a function through a function pointer?

We already know how to call a function in C Language. Now, we will see how to call a function using a function pointer. Suppose we declare a function as follows:
int fun(int , int);

We can call the above function as follows:
int result = fun(10 , 20);

We can also call the above function using a function pointer as follows:
int result = (*IP)(10, 20); // Calling a function using function pointer.
OR
int result = IP(10,20); // Calling a function using function pointer by removing the indirection operator

Note: If we are using a function pointer to call a function in C Language, we can omit the indirection operator as we did in the second case. But, it is recommended to use the indirection operator as it makes it clear to the user that we are using a function pointer.

Program to Understand Function Pointer in C Language:
#include <stdio.h>
int Addition(int, int);
int main()
{
    int a, b;
    int (*IP) (int, int);
    printf ("Enter Two Numbers : ");
    scanf ("%d %d", &a, &b);
    IP = Addition;
    int result = (*IP) (a, b);
    printf ("Result : %d", result);
    return 0;
}
int Addition(int a, int b)
{
    int c = a + b;
    return c;
}
Output:
Program to Understand Function Pointer in C Language
More Programs to Understand Function Pointer:
#include<stdio.h>
void abc ()
{
    printf ("Hello World\n ");
}
void main ()
{
    void (*ptr) (void);
    ptr = &abc;
    ptr ();
}

Output: Hello World

Passing a function’s address as an argument to another function in C:

It is also possible in C Language that we can pass the address of a function as an argument to other functions in the same way we send other arguments to the function. Let us understand this with an example.

In the below example, we have created two functions, i.e., Function1 and Function2. The Function1 function contains the function pointer as an argument. In the main() method, the Function1 method is called in which we pass the address of Function2. When Function1 is called, the pointer ptr contains the address of the Function2 function. Inside Function1, we call the Function2 method by using the function pointer.

#include <stdio.h>
void Function1(void (*ptr) ());
void Function2();
int main()
{
    Function1(Function2);
    return 0;
}
void Function1(void (*ptr) ())
{
    printf ("Function1 is called");
    (*ptr) ();
}
void Function2()
{
    printf ("\nFunction2 is called");
}
Output:
Passing a function's address as an argument to another function in C
]]>
4301
Dangling Pointer in C Programming https://shishirkant.com/dangling-pointer-in-c-programming/?utm_source=rss&utm_medium=rss&utm_campaign=dangling-pointer-in-c-programming Mon, 04 Sep 2023 17:15:21 +0000 https://shishirkant.com/?p=4298 Dangling Pointer in C Language:

The most common bugs related to pointers and memory management in C Programming Language is Dangling/Wild Pointers. Sometimes as a programmer, we forgot to initialize the pointer with a valid address, and when we do so, then this type of uninitialized pointer is known as a dangling pointer. Dangling pointer occurs at the time of the object destruction when the object is deleted or de-allocated from memory without modifying the value of the pointer. In this case, the pointer is pointing to the memory, which is de-allocated.

The pointer variable which is pointing to an inactive or dead memory location is called Dangling Pointer. Or in other words, we can say that a pointer pointing to a memory location that has been deleted (or freed) is called a dangling pointer in the C language. For a better understanding, please have a look at the below diagram.

Dangling Pointer in C Language with Examples

In the above diagram, you can see we have three-pointers and observe that Pointer 3 is a dangling pointer. Pointer 1 and Pointer 2 are the pointers that point to the allocated objects, i.e., Object 1 and Object 2, respectively whereas Pointer 3 is a dangling pointer as it points to a deleted object.

How to Create Dangling Pointer in C Language?

In C Programming Language, there are three different ways where we can make a pointer acts as a dangling pointer. They are as follows:

  • De-allocation of memory
  • Function Call
  • Variable goes out of scope
Creating Dangling Pointer by De-Allocating the Memory:

Deallocating a memory that is pointed by a pointer causes a dangling pointer. In the below example, we have created an integer pointer. Then we call the free function by passing the pointer. Once we call the free function, then the pointer ptr becomes a dangling pointer.

#include <stdlib.h>
#include <stdio.h>
int main()
{
    int *ptr = (int *)malloc(sizeof(int));
    free(ptr);
}
Avoiding Dangling Pointer Errors in C Language:

In C Programming Language, the dangling pointer errors can be avoided by initializing the pointer to a NULL value. If we assign the NULL value to the pointer, then the pointer will not point to the de-allocated memory instead the pointer is not pointing to any memory location. So, in the below example, after calling the free function, we initialize the pointer with a NULL value and hence it is not a Dangling Pointer anymore.

#include <stdlib.h>
#include <stdio.h>
int main()
{
    int *ptr = (int *)malloc(sizeof(int));
    free(ptr);
    ptr = NULL;
}
Creating Dangling Pointer by Function Call:

In C Language, the pointer pointing to the local variable becomes dangling when the local variable is not static. In the below example, the variable x is a local variable and goes out of scope once the execution of the fun() function is completed. And inside the main method, the pointer p is pointing to something which does not exist anymore and hence the pointer ptr becomes a dangling pointer.

#include<stdio.h>
int *fun()
{
    int x = 5;
    return &x;
}
int main()
{
    int *ptr = fun ();
    printf ("%d", *ptr);
    return 0;
}

Output: A garbage Address

In the above program, ptr is called a Dangling Pointer because according to the storage class of C, by default any type of variable storage class specifier is auto, and the lifetime of the auto variable is within the body only. But in the program, the control is passed back to the main function and still, the pointer is pointing to that inactive variable only.

The solution of the dangling pointer is in place of creating an auto variable, create a static variable because the lifetime of the static variable is the entire program. Let us modify the program as follows where we make the variable x static. Once we make variable x static, now the variable x has scope throughout the program. So, the point that you need to remember is, that the pointer pointing to the local variable doesn’t become a dangling pointer when the local variable is static.

#include<stdio.h>
int *fun()
{
    static int x = 5;
    return &x;
}
int main()
{
    int *ptr = fun ();
    printf ("%d", *ptr);
    return 0;
}

Output: 5

Creating Dangling Pointer by Variable goes out of scope:

When the variable goes out of scope, then the pointer becomes a dangling pointer. In the below example, first, we created one pointer ptr. Then with the variable scope, we initialized the pointer. Once the variable goes out of scope, then it becomes a dangling pointer

#include<stdio.h>
void main()
{
    int *ptr;
    //Variable scope started
    {
        int ch;
        ptr = &ch;
    }
    //Variable scope ended
    // Now ptr is dangling pointer
    printf ("%d", *ptr);
    return 0;
}
]]>
4298
How to Pass Structure as a Parameter to a Function in C https://shishirkant.com/how-to-pass-structure-as-a-parameter-to-a-function-in-c/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-pass-structure-as-a-parameter-to-a-function-in-c Mon, 04 Sep 2023 17:11:25 +0000 https://shishirkant.com/?p=4293 Passing Structure as a Parameter to a Function using Call by Value in C Language:

Let us understand how to pass a structure as a parameter to a function using the call by value mechanism in C Language. For a better understanding of this let us first create a structure as shown below. As you can see in the below image, we have a structure called Rectangle having two properties length and breadth.

Passing Structure as a Parameter using Call by Value

Now we need to create a function called CalculateArea which should calculate the area of a rectangle. Now here, shall we pass length separate and breadth separate? No need, we can send the structure itself as a parameter and that is the benefit of using a structure. We can send the structure itself and the structure is carrying both length and breadth. For a better understanding, please have a look at the below image.

Structure as Parameter

Now in the main function, we need to create a variable of type structure and then we need to pass that structure as a parameter to the CalculateArea function as shown in the below image.

Passing Structure as a Parameter using Call by Value
The complete code is given below.
#include <stdio.h>
struct Rectangle
{
    int length;
    int breadth;
};
int CalculateArea (struct Rectangle rect2)
{
    return rect2.length * rect2.breadth;
}
int main ()
{
    struct Rectangle rect1 = { 10, 5 };
    printf ("%d", CalculateArea (rect1));
}
Code Explanation and Memory Representation:

Within the main function, first, we created a variable rect1 of type structure rectangle and it initialized it with values 10 and 5. Here 10 will be assigned to length and 20 will be assigned to breadth. Then we call the function CalculateArea by giving the structure rect1 as a parameter. In the CalculateArea function, we defined one parameter of type structure Rectangle and this parameter is called by value as we have not specified either * or &.

As we already discussed in our previous article, in passed-by value, new memory allocation will happen and the values are copied. So, here a new rectangle object rect2 will be created and the values 10 and 5 are copied to the length and breadth properties. Then the CalculateArea function calculates the area and returns that value and that value will be printed in the console window. For better understanding, please have a look at the below diagram.

Passing Structure as a Parameter using Call by Value Memory Representation

Now inside the CalculateArea function, if we make changes to the rect2 object, then it will not affect the rect1 object inside the main method. This is because in the call by the value we are just passing a copy of the value. For a better understanding, please have a look at the below code.

#include <stdio.h>
struct Rectangle
{
    int length;
    int breadth;
};
int CalculateArea (struct Rectangle rect2)
{
    rect2.length = 20;
    rect2.breadth = 15;
    return rect2.length * rect2.breadth;
}
int main ()
{
    struct Rectangle rect1 = { 10, 5 };
    printf ("%d", CalculateArea (rect1));
}

The following image is the memory representation of the above example.

how to pass a structure to a function using call by value
Passing Structure as a Parameter to a Function using Call by Address in C Language

Let us understand How to Pass Structure as a Parameter to a Function using Call by Address in C Language with an example. Now our requirement is to change the length of a rectangle. We can change the length itself within the main function but we don’t want to do any business operations within the main method. The main function role is simply to assign the task or manage the task. So, when you want to modify the actual parameter then it should be called by address or call by reference. For better understanding, please have a look at the following code.

#include <stdio.h>
struct Rectangle
{
    int length;
    int breadth;
};
void changelength(struct Rectangle *p)
{
    p->length = 20;
}
int main ()
{
    struct Rectangle r = { 10, 5 };
    changelength(&r);
}

As you can see in the above, within the main function, first we create an object of struct Rectangle and assigned it with 10 and 5. Then we call the changelength function by passing the & of the rectangle object i.e. &r. We also know the point is only responsible to hold the address. So, in the changelength function, we create one parameter of type structure pointer i.e. struct Rectangle *p. That means the pointer p now points to the rectangle r object. for accessing the structure member indirectly using pointer we have to use -> operator i.e. p -> length = 20; this length would be modified to 20 in the structure object. Following is the memory representation of the above example.

Passing Structure as a Parameter using Call by Address
]]>
4293
How to Pass Array as a Parameter to a Function in C https://shishirkant.com/how-to-pass-array-as-a-parameter-to-a-function-in-c/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-pass-array-as-a-parameter-to-a-function-in-c Mon, 04 Sep 2023 17:07:28 +0000 https://shishirkant.com/?p=4289 Passing Array as a Parameter to a Function in C Language:

Let us understand this directly with an example. Please have a look at the following example. As you can see in the below code, the main function is having an array of size 5 and it is also initialized with five elements (2,4,6,8,10). The name of the array is A. Then we are calling a function i.e. fun by passing that array A and an integer number that represents the size of the array. The fun function is taking two parameters. The first parameter is an array i.e. B and for passing an array as a parameter we need to mention empty brackets [] and we should not give any size. The fun function doesn’t know the size of the array because the array actually belongs to the main function. So, we should also pass what is the size of the array and for that, the second parameter i.e. n is being used. So, this B is actually a pointer to an array. It is not an array itself, it’s a pointer to an array. Within the function, using a for loop, we are printing all the elements of the array.

#include <stdio.h>
void fun (int B[], int n)
{
    int i;
    for (i = 0; i < n; i++)
    {
        printf ("%d", B[i]);
    }
}
int main ()
{
    int A[5] = { 2, 4, 6, 8, 10 };
    fun (A, 5);
}
What parameter passing method is used in the above example?

The point that you need to remember is an array is always passed by address not by the value both in C and C++ Language. That means the base address of the array A is given to the pointer i.e. to B. Here B is just a pointer and giving bracket means it is a pointer to an array. The second parameter is n and if you notice there is no ‘*’ then it is not called by address and there is no ‘&’ then it is not called by reference. That means it is the call by value like just a normal variable. So, there are two parameters one is passed by address and another one is passed by value.

Can we write * instead of []?

Yes, we can. Instead of writing brackets, even you can write ‘*’ there as shown in the below code. Here, B is an integer pointer that will be pointing to an array.

#include <stdio.h>
void fun (int *B, int n)
{
    int i;
    for (i = 0; i < n; i++)
    {
        printf ("%d", B[i]);
    }
}
int main ()
{
    int A[5] = { 2, 4, 6, 8, 10 };
    fun (A, 5);
}
What is the difference between *B and B[]?

The difference is that *B is an integer pointer that can point to an integer variable as well as it can also point to an integer array. On the other hand, B[] is a pointer that can only point to an integer array and cannot point to an integer variable.

One more point that you need to understand, within the fun function, if you do any modification to the array then it will reflect the same in the main function as the array uses the pass-by address mechanism. Let us understand this with an example.

#include <stdio.h>
void fun (int *B)
{
    B[0] = 20;
    B[2] = 30;
}
int main ()
{
    int A[5] = { 2, 4, 6, 8, 10 };
    fun (A);
    for (int i = 0; i < 5; i++)
    {
        printf ("%d ", A[i]);
    }
}
Returning an Array from a Method in C Language:

The C programming language does not allow to return of an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array’s name without an index.

In order to understand this, please have a look at the below code. As you can see in the below code, inside the main function we have a pointer variable *A. Then the main function calls the fun function by passing a value of 5. The fun function which is taking parameter ‘n’ will store the incoming value 5 and this is passed by the value mechanism. The fun function is also having a pointer variable i.e. *p and it is allocating an array of size of type integer * 5 in the heap area. We already discussed malloc function allocates memory in the heap area. In the heap area, it creates an array with size five and stores the base address of that array in the integer pointer i.e. *p.

#include <stdio.h>
int* fun(int n)
{
    int *p;
    p = (int *) malloc (n * sizeof (int));
    return (p);
}
int main ()
{
    int *A;
    A = fun (5);
}
How does it work?

The program execution starts from the main method. The main method first creates an integer pointer variable. The integer pointer variable can point to normal variables as well as to an array. Then it is calling the function fun() by passing 5 as the value.

The fun function is taking a parameter n and the value 5 will store in it. Then the malloc() function will allocate the memory in the heap and inside the heap, an array of size 5 will be created. The address of that array will be present in ‘p’. And after allocating the memory in the heap and storing the base address in point variable p, it returns that pointer variable i.e. the base address of the array whose memory is allocated in the heap.

Inside the main function, now the pointer variable i.e. A will point to the array which is created in the heap memory. For a better understanding please have a look at the below image.

Array as Parameter
]]>
4289
Pointer to Structure in C Programming https://shishirkant.com/pointer-to-structure-in-c-programming/?utm_source=rss&utm_medium=rss&utm_campaign=pointer-to-structure-in-c-programming Mon, 04 Sep 2023 17:03:11 +0000 https://shishirkant.com/?p=4286 Let us understand How to Access a Structure using a Pointer in C Language with an example

First, we will see how to access the structure using normal variables, and then we will see how to access the structure using pointer variables. Please have a look at the following code example.

#include <stdio.h>
struct Rectangle
{
    int length;
    int breadth;
};
int main ()
{
    struct Rectangle r = {10, 5};
    r.length = 20;
    r.breadth = 30;
}

As you can see in the above code, we have a structure Rectangle with two members i.e. length and breadth. Inside the main method, we created a data variable of type structure (struct Rectangle r = {10, 5};) and assign the length and breadth member values as 10 and 5. Then we access the structure members (length and breadth) using dot (.) operator i.e. (r.length = 20; and r.breadth = 30;).

Now, let us see how to access the structure using a pointer. So, for this first, we need to create a pointer of type structure and then we need to be initialized the pointer to the address of the structure variable as shown in the below two lines of code.

Pointer to Structure

As you can see, the pointer variable type is struct Rectangle, so it is going to hold the address of a structure variable. Further, if you notice the pointer variable holding the address of r.

Note Every pointer, whatever the type it has, the pointer will take 2bytes. Actually, it takes equal to the size of the integer in any compiler. If an integer takes 2bytes, the compiler pointer also takes 2bytes, if an integer takes 4bytes it will also take 4bytes. Here, we are assuming the integer takes 2 bytes,

How to Access Structure Members using a Pointer in C Language?

As of now, we have discussed two things. First, create a structure variable. Then create a pointer variable of structure type and assign it with the structure address. Now let us move and see what are the different ways to access the structure members using a pointer. We cannot access directly using the dot operator as shown below

p.length = 20;
p.breadth = 30;

This is because p is a pointer, it’s not a variable. The pointer holds the address not the values directly. So, we need to go to the place where the pointer is pointing i.e. to the base address of the structure variable r, and then access the data members. To do so we need to write the pointer using * as shown below.

*p.length = 20;
*p.breadth = 30;

Again, this is also not going to work and you will get an error. This is because the priority of the dot (.) operator is higher than the * operator. So, first, it will try to access the values and hence you will get the error. To overcome this error put *p inside a bracket and then call the structure member as shown below.

(*p).length = 20;
(*p).breadth = 30;

With the above changes in place, now it will work as expected. We have to write this much code to access the structure members. Instead of this syntax, the C programming language gives a simple syntax for accessing the members using a pointer as shown below.

p -> length = 20;
p -> breadth = 30;

As you can see in the above, using the pointer variable and arrow (->) operator we can access the members. The complete code is given below.

#include <stdio.h>
struct Rectangle
{
    int length;
    int breadth;
};
int main ()
{
    struct Rectangle r = {10, 5};
    struct Rectangle *p = &r;

    p -> length = 20;
    p -> breadth = 30;

    int Area = p -> length * p -> breadth;
    printf("%d",Area);
}
How do get the memory in the heap?

Now one more thing we will do, we will create an object dynamically in the heap using a pointer. Here, we’ll create an object or a variable of type rectangle dynamically in the Heap memory. Let us discuss this step by step.

Step1: Create a pointer variable

First, we need to create a pointer variable of type structure as shown below. This pointer variable is created inside the stack frame of the main memory.

struct Rectangle *p;

Step2: Allocating Memory in Heap

We need to create the rectangle object or variable in the heap memory. As we already discussed to create the memory in the heap we need to use the Malloc function. For the malloc function, we need to specify the size that we want in the heap memory. Here size is nothing but the size of the structure. Again, the malloc function returns a void pointer, so we need to typecast struct Rectangle pointer. The following line of code does the same.

p=(struct Rectangle *) malloc(sizeof (struct Rectangle));

The above line will allocate an object of type Rectangle in the heap.

Step3: Accessing the Members:

Now using the arrow operator, you can access and modify the structure members as shown below.

p -> length=10;
p -> breadth=5;

The Complete code is given below.
#include <stdio.h>
#include <stdlib.h>
struct Rectangle
{
    int length;
    int breadth;
};
int main ()
{
    struct Rectangle *p;
    p=(struct Rectangle *) malloc(sizeof (struct Rectangle));
    p -> length=10;
    p -> breadth=5;
    int Area = p -> length * p -> breadth;
    printf("%d", Area);
}
Memory Representation:

The Pointer variable is created in the stack and the rectangle object is created in the heap and the pointer points to the heap memory. For a better understanding, please have a look at the below image.

How to access structure members using a pointer?
]]>
4286
Error Handling in C Programming https://shishirkant.com/error-handling-in-c-programming/?utm_source=rss&utm_medium=rss&utm_campaign=error-handling-in-c-programming Mon, 04 Sep 2023 16:56:11 +0000 https://shishirkant.com/?p=4282 Error Handling in C Program:

There is no direct support for Error Handling in C language. However, using the return statement in a function, there are few methods and variables defined in error.h header file that can be used to point out the error.  A programmer has to prevent errors in the first place before testing return values from the functions.  In C, the function return NULL or -1 value in case of any error. There is a global variable errno which sets the error code/number. Hence, while programming the return value can be used to check error.

What is errno?

When a function is called in C, a variable named errno is automatically assigned a code (value) which can be used to identify the type of error that has been encountered. It is a global variable indicating the error occurred during any function call and defined in the header file errno.h.

List of few different errno values and its corresponding meaning:
errno values and its corresponding meaning in C Language
Example:
#include <stdio.h>
#include <errno.h>
int main ()
{
    FILE *fp;
    fp = fopen ("File.txt", "r");
    printf (" Value of errno: %d\n ", errno);
    return 0;
}

Output:

Error Handling in C Program
Functions used to display a text message associated with errorno

perror(): It returns the string you pass to it, followed by a colon, a space, and then the textual representation of the current errno value.

Syntax: void perror (const char *str) where str is a string containing a message to be printed.

strerror(): It returns a pointer to the textual representation of the current errno value.

Syntax: char *strerror (int errnum) where errnum is the error number.

Example
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main ()
{
    FILE *fp;
    fp = fopen (" File.txt ", "r");
    printf ("Value of errno: %d\n", errno);
    printf ("The error message is : %s\n", strerror (errno));
    perror ("Message from perror");
    return 0;
}

Output:

How to Handle Error in C Programming Language
Divide by Zero Error in C Program

Sometimes at the time of dividing any number, programmers do not check if a divisor is zero and finally it creates a runtime error. Because C Language cannot do anything about it. All you can do is, avoid it.

Example
#include<stdio.h>
#include <stdlib.h>
void function (int);
int main ()
{
    int x = 0;
    function (x);
    return 0;
}
void function (int x)
{
    float fx;
    if (x == 0)
    {
        printf ("Division by Zero is not allowed \n");
        fprintf (stderr, "Division by zero! Exiting...\n");
        exit (EXIT_FAILURE);
    }
    else
    {
        fx = 10 / x;
        printf ("f(x) is: %.5f", fx);
    }
}

Output:

Divide by Zero Error in C Program
Exit Status

The Exit Status constants are used in the exit() function to inform the calling function about the error. EXIT_SUCCESS and EXIT_FAILURE are the two constant values available for use. These are macros defined in stdlib.h which indicates successful or unsuccessful termination, respectively.

Example
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
int main ()
{
    FILE *fp;
    fp = fopen ("filedoesnotexist.txt", "rb");
    if (fp == NULL)
    {
        printf ("Value of errno: %d\n", errno);
        printf ("Error opening the file: %s\n", strerror (errno));
        perror ("Error printed by perror");
        exit (EXIT_FAILURE);
        printf ("I will not be printed\n");
    }
    else
    {
        fclose (fp);
        exit (EXIT_SUCCESS);
        printf ("I will not be printed\n");
    }
    return 0;
}

Output:

Error Handling in C Program with Examples
]]>
4282
File Handling in C Language https://shishirkant.com/file-handling-in-c-language/?utm_source=rss&utm_medium=rss&utm_campaign=file-handling-in-c-language Mon, 04 Sep 2023 16:04:04 +0000 https://shishirkant.com/?p=4278 What is a File?

A file is the name of a physical memory location in the secondary storage area. The file contains a sequence of bytes of data in the secondary storage area in the form of an unstructured manner. In the implementation, when we were required to interact with the secondary storage area, then recommended going for file operations. By using files, primary memory-related data can be sent to the secondary storage area and secondary storage area information can be loaded to primary memory. In ‘C’ programming language, IO Operations are classified into two types:

  1. Standard IO Operations
  2. Secondary IO Operations

When we are interacting with Secondary IO devices, then it is called Secondary IO Operations. Standard IO related and Secondary IO related, all predefined functions are declared in stdio.h only.

Why files are needed?

The entire data is lost, when a program is terminated. Storing the data in a file will preserve your data once the program is terminated. It will take a lot of time to enter a large number of data. However, if you’ve got a file containing all the information, you’ll easily access the contents of the file using a few commands in C. Without any prior changes, you can easily move your data from one computer to another.

Types of Files

When handling files, there are two sorts of files you ought to know about:

  1. Text files
  2. Binary files
Text files

Text files are the normal .txt files. You can easily create text files using any simple text editor like Notepad. When you open those files, you will see all the contents within the file as plain text. You can easily edit or delete the contents. They take minimum effort to for easily readable, supply the smallest amount of security, and take bigger space for storing. In the Text files, data is represented with the help of ASCII values, i.e., .txt, .c, .cpp

Binary files

Binary files are mostly the .bin files on your computer. Instead of storing data in plain text, they store it within the binary form (0’s and 1’s). They can hold a better amount of knowledge, aren’t readable easily, and provides better security than text files. In binary Files, data is represented with the help of byte, i.e., .exe, .mp3, .mp4, .jpeg

Points to Remember:
  1. To specify that a given file is being opened or created in “text mode” then append “t” to the string mode. Examples: rt, wt, at, rt+, wt+, at+
  2. To specify the binary mode, append “b” to the end of the string mode. Example: RB. Wb, ab, r+b, w+b, a+b
  3. “fopen” and “fsopen” also allow that “t” or “b” to be inserted between the letter and the ‘t’ character in the string. Example: rt+ is equivalent to r+t.
  4. If “t” or “b” is not giving in the string, the mode is governed by “f” mode, if “f” mode is set to O_BINARY, files are opened in BINARY mode.
  5. If “f” mode is set to O_TEXT, they are opened in text mode. These constants are defined in fcntl.h
File Operations

In C, you’ll perform four major operations on files, either text or binary:

  1. Creating a new file
  2. Opening an existing file
  3. Closing a file
  4. Reading from a file and writing information to a file
Example:
#include<stdio.h>
#include<dos.h>
#include<stdlib.h>
int main()
{
    FILE* fp;
    fp = fopen("F:\\1.txt","w");
    if(fp == NULL)
    {
       printf("\n Unable to create File");
       return EXIT_FAILURE;
    }
    fprintf(fp,"Welcome");
    fprintf(fp,"\n%d HELLO WORLD %f", 100, 12.50);
    fclose(fp);
    return EXIT_SUCCESS;
}
Output:
File Handling in C Language with Examples
Points to Remember:
  1. When we are opening a file, two parameters must be passed: Path and Mode
  2. The file may open or may not open. If open, then it returns ADDRESS. If not, then it returns NULL.
  3. stdio.h provides the standard IO Related predefined function prototype.
  4. conio.h provides the Console Related predefined function prototype.
  5. FILE is a predefined structure that is available in stdio.h. By using the FILE structure, we can handle file properties. The size of the FILE structure is 16 bytes.
  6. fp is a variable of type FILE*, which maintains the address of FILE. The size of fp is 2 bytes because it holds an address.
fopen()

It is a predefined function, which is declared in stdio.h, by using this function we can open a file in a specific path with a specific mode. It requires two arguments of type const char*. On success, fopen() returns FILE*, on failure returns NULL. Generally, fopen() is failed to open FILE in the following cases:

  1. The path is incorrect.
  2. Mode is incorrect
  3. Permissions are not available
  4. Memory is not available

Syntax: FILe *fopen(const char* path, const char* mode);

fprintf()

By using this predefined function, we can write the content in the file. fprintf() can take any number of arguments but the first argument must be FILE* and the remaining arguments are of any path.

Syntax: int fprintf(FILE* stream, const char*path,…..);

fclose()

By using this predefined function, we can close the file after saving data. fclose() requires one argument of type FILE* and returns an int value.

Syntax: int fclose(FILE* stream);

File Modes

Always FILE modes will indicate for what purpose the file needs to be opened or created. File modes are classified into three types:

  1. Write
  2. Read
  3. Append

Depending on operations, file modes are classified into 6 types:

  1. Write(w): Create a file for writing, if the file already exists, then it will override (the old file is deleted and a new file is created). In “w” mode, whether the file exists or not, always a new file is constructed.
  2. Read(r): Open an existing file for reading, if file not exists then fopen() returns NULL. When we are working with “r” mode, if the file doesn’t exist, a new file is not constructed.
  3. Append(a): Open an existing file for appending (write the data at end of the file) or create a new file for writing if it doesn’t exist. When we are working with “a”, if file doesn’t exist, then only a new file is constructed.
  4. w+ (write and read): Create a file for update i.e. write and read if the file already exists then it will override. In w+ mode, if the file is available or not, always a new file is constructed.
  5. r+ (read and write): Open an existing file for update I.e. read and write. Generally, “r+” mode is required, when we need to update existing information. In “r+” mode, if the file doesn’t exist, a new file is not constructed.
  6. a+ (w+ and r+): Open an existing file for update or create a new file for update. By using a+ mode, we can perform random operations.
Program For Reading Data From Files using C Language
#include<stdio.h>
#include<stdlib.h>
int main()
{
    FILE* fp;
    char ch;
    fp = fopen("F:\\1.txt","r");
    if(fp == NULL)
    {
       printf("\n File not Found");
       return EXIT_FAILURE;
    }
    while(1)
    {
       fscanf(fp,"%c",&ch);
       if(feof(fp)) //if(ch == EOF)
          break;
       printf("%c",ch);
    }
    fclose(fp);
    return EXIT_SUCCESS;
}
Output:
Program For Reading Data From Files using C Language
fscanf()

It is a predefined function that is declared in stdio.h, by using this function, we can read the data from a file. fscanf() can take any number of arguments but the first argument must be and the remaining arguments should be scanf() function format. When we are working with fscanf() function, it can read the entire content of the file except.

Syntax: int fscanf(FILE* stream, const char” format,…..);

feof()

By using this function, we can find the end of the character position. It requires one argument of type FILE* and returns an int value. When the file pointer is pointing to the EOF character then it returns a non-zero value, if it is pointing to other than the EOF character then it returns zero.

Syntax: int feof(FILE* stream);

fgetc()

It is a predefined unformatted function that is declared in stdio.h, by using this function we can read the data from a file including EOF characters also. It returns an int value i.e. ASCII value of a character.

Syntax: int getc(FILE* stream);

Program for Reading a line from a file and displaying it using C Language
#include <stdio.h>
#include <stdlib.h> // For exit() function
int main() {
    char c[1000];
    FILE *fptr;
    if ((fptr = fopen("F:\\1.txt", "r")) == NULL) {
        printf("Error! opening file");
        // Program exits if file pointer returns NULL.
        exit(1);
    }
    // reads text until newline is encountered
    fscanf(fptr, "%[^\n]", c);
    printf("Data from the file:\n%s", c);
    fclose(fptr);
    return 0;
}
Output
Program for Reading a line from a file and displaying it using C Language
Example to understand File Handling in C Language:
#include<stdio.h>
#include<conio.h>
int main()
{
    FILE* fp;
    char path[50];
    char str[50];
    fprintf(stdout, "Enter a file path : ");
    gets(path);
    fp = fopen(path,”a");
    if(fp == NULL)
    {
       fprintf(stderr, "Unable o create file");
       getch();
       return 1;
    }
    printf("Enter a String : ");
    fflush(stdin);
    gets(str);
    fputs(str, fp);
    fclose(fp);
    return 0;
}
Output
Example to understand File Handling in C Language
1.txt
File Handling in C Language with Examples
Delay in File Handling

It is a predefined function that is declared in dos.h. By using this function, we can suspend the program from execution. The delay() function requires one argument of type unsigned integer i.e. milliseconds value. By using delay(), we can suspend the program for a minimum of 1 sec and a maximum of 5 sec.

Syntax: void delay(unsigned milliseconds);

sleep()

It is a predefined function that is declared in dos.h. By using this function, we can suspend the program execution sleep() function requires one argument of type unsigned integer seconds format data.

Syntax: void sleep(unsigned seconds);

stdout: It is a global pointer variable that is defined in stdio.h. By using this global pointer, we can handle the standard output buffer.

stdin: By using this global pointer, we can handle the standard input buffer.

stderr: By using this global pointer, we can handle standard IO Related errors. When we are working with stderr, it will redirect the data back to stdout.

stdprn: By using this global pointer, we can handle the printer.

fseek()

By using this predefined function, we can create the movement in the file pointer. fseek() requires three arguments of type FILE*, long integer, and an integer type.

Syntax: int fseek(FILE* stream, long offset, int whence);

Where stream will provide file information, Offset is the number of bytes, and whence value is file pointer location. The whence value can be recognized by using the following constant values:

  1. SEEK_SET: This constant will pass the file pointer to the beginning of the file.
  2. SEEK_CUR: This constant will provide the constant position of the file pointer.
  3. SEEK_END: This constant value will send the file pointer to the end of the file.

These constant values can be recognized using INTEGER values also.

  1. SEEK_SET value is 0.
  2. SEEK_CUR value is 1.
  3. SEEK_END value is 2.
rewind()

By using this predefined function, we can send the control to the beginning of the file. rewind() requires one argument of type FILE*.

Syntax : void rewind(FILE* stream);

The behavior of rewind() is similar to – fseek(FILE*, O, SEEK_SET)

ftell()

By using this predefined function, we can find the size of the file. ftell() requires one argument of type FILE* and returns a long integer value. Generally, ftell() returns file pointer position, so if the file pointer is pointing to the end of the character then it is equal to the size of the file.

Syntax: long ftell(FILE* stream);

remove()

By using this predefined function, we can delete two files permanently from the hard disk. remove() requires one argument of type constant char* and returns an int value.

Syntax: int remove(const char* filename);

rename()

By using this predefined function, we can change the name of an existing file. rename() function requires two types of arguments of type const char and returns an int value.

Syntax: int rename(const char* oldname, const char* newname);

Program to Reverse the string data present in a file using C Language
#include<stdio.h>
#include<string.h>
#include<malloc.h>
int main()
{
    FILE *fp;
    char path[50];
    long int fsize, i = 0;
    char *str;
    char ch;
    printf ("Enter a file path :");
    gets (path);
    fp = fopen (path, "rt");
    if (fp == NULL)
    {
        printf ("\n File not found");
        return 1;
    }
    fseek (fp, 0, SEEK_END);
    fsize = ftell (fp);
    fseek (fp, 0, SEEK_SET);
    str = (char *) calloc (fsize, sizeof (char));
    while (1)
    {
        ch = fgetc (fp);
        if (feof (fp))
         break;
        str[i++] = ch;
    }
    str[i] = '\o';
    fclose (fp);
    remove (path);
    strrev (str);
    fp = fopen (path, "wt");
    fputs (str, fp);
    fclose (fp);
    free (str);
    str = NULL;
    return 0;
}
Output
Program to Reverse the string data present in a file using C Language
1.txt
Reverse the string data present in a file
Program to Find and Update (or Replace) a Character in a File using C Language
#include<stdio.h>
#include<stdlib.h>
int main()
{
    FILE *fp;
    char path[50];
    char ch, sch, dch;
    printf ("Enter a file path : ");
    gets (path);
    fp = fopen (path, "rt+");
    if (fp == NULL)
    {
        printf ("File not found");
        return 1;
    }
    printf ("\n Enter a source character(s) : ");
    fflush (stdin);
    sch = getchar ();
    printf ("\n Enter a destination character(D) : ");
    fflush (stdin);
    dch = getchar ();
    while (1)
    {
        ch = fgetc (fp);
        if (ch == EOF)
         break;
        if (ch == sch)
        {
            fseek (fp, -1, SEEK_CUR);
            fprintf (fp, "%c", dch);
            fseek (fp, 0, SEEK_CUR);
        }
    }
    fclose (fp);
    return 0;
}

Output
Program to Find and Update (or Replace) a Character in a File using C Language
2.txt
Find and Update a Character in a File
Program for Encoding and Decoding using C Language

#include<stdio.h>
include<conio.h>
int main()
{
    FILE *fp;
    int flag, code = 0;
    char path[30];
    char ch;
    printf ("Enter a file path : ");
    gets (path);
    fp = fopen (path, "r+");
    
    if (fp == NULL)
    {
        printf ("\n File not found");
        getch ();
        return 1;
    }
    
    do
    {
        printf ("\n 1 for ENCODE : ");
        printf ("\n 2 for DECODE : ");
        scanf ("%d", &flag);
    }
    while (flag != 1 && flag != 2);
    
    if (flag == 1)
        code = 40;
    else
        code = -40;
        
    while (1)
    {
        ch = fgetc (fp);
        if (ch == EOF)
         break;
        if(ch != '\n' && ch != '\r')
        {
         fseek (fp, -1, SEEK_CUR);
         fprintf (fp, "%c", ch + code);
         fseek (fp, 0, SEEK_CUR);
        }
    }
    fclose (fp);
    return 0;
}

Output
Program for Encoding and Decoding using C Language
2.txt (after Encoding)
Program for Encoding and Decoding using C
2.txt (after Decoding)
Program for Encoding and Decoding
Program for Operations on Audio File using C Language

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define f1 "F:\\part1.mp3"
#define f2 "F:\\part2.mp3"
#define f3 "F:\\part3.mp3"
#define f4 "F:\\part4.mp3"
int main(void)
{
    FILE *sfp;
    FILE *dfp;
    char spath[30];
    char dpath[4][30] = { f1, f2, f3, f4 };
    long int fsize = 0, nb = 0; // nb is number of bytes
    int i = 0;
    char ch;
    printf ("\n Enter sfp path : ");
    gets (spath);
    if (sfp == NULL)
    {
        printf ("\n %s NOT FOUND", spath);
        return EXIT_FAILURE;
    }
    fseek (sfp, 0, SEEK_END);
    fsize = ftell (sfp);
    rewind (sfp);
    dfp = fopen (dpath[i], "wb");
    
    if (dfp == NULL)
    {
        fclose (sfp);
        printf ("\n%s Unable to create");
        return EXIT_FAILURE;
    }
    
    while (1)
    {
        ch = fgetc (sfp);
        if (feof (sfp))
         break;
        fprintf (dfp, "%c", ch);
        ++nb;
        if (nb = fsize / 4 && i != 3)
        {
            fclose (dfp);
            nb = 0;
            ++i;
            dfp = fopen (dpath[i], "wb");
            if (dfp == NULL)
            {
                printf ("\n %s Unable to create", dpath[i]);
                fclose (sfp);
                return EXIT_FAILURE;
            }
        }
    }
    fclose (sfp);
    fclose (dfp);
    return EXIT_SUCCESS;
}

Output
Program for Operations on Audio File using C Language
Program to combine two or more audio files together using C Language
#include<stdlib.h>
#define f1 "F:\\part1.mp3"
#define f2 "F:\\part2.mp3"
#define f3 "F:\\part3.mp3"
#define f4 "F:\\part4.mp3"
int main(void)
{
    FILE *sfp;
    FILE *dfp;
    char dpath[30];
    char spath[4][30] = { f1, f2, f3, f4 };
    int i = 0;
    char ch;
    printf ("\n enter dfp path : ");
    gets (dpath);
    dfp = fopen (dpath, "wb");
    if (dfp == NULL)
    {
        printf ("\n%sUnable to create", dpath);
        return EXIT_SUCCESS;
    }

   for (i = 0; i < 4; i++)
   {
       sfp = fopen (spath[i], "rb");   
       if (sfp == NULL)
       {
           fclose (dfp);
           printf ("\n%s Not Found", spath[i]);
           return EXIT_FAILURE;
       }

       while (1)
       {
           ch = fgetc (sfp);
           if (feof (sfp))
              break;
           fprintf (dfp, "%c", ch);
       }
       fclose (sfp);
   }
   fclose (dfp);
   return EXIT_SUCCESS;
}
Output
File Handling in C Language with Examples
]]>
4278
Dynamic Array Creation in C Programming https://shishirkant.com/dynamic-array-creation-in-c-programming/?utm_source=rss&utm_medium=rss&utm_campaign=dynamic-array-creation-in-c-programming Mon, 04 Sep 2023 15:32:35 +0000 https://shishirkant.com/?p=4275 Dynamic Array:

Static array variables are fixed in size. They are linked in the data area or stack area or in the const area depending on the declaration. Now, this element group is fixed and cannot be changed. To affect this shortcoming dynamic arrays are often defined. Dynamic array is nothing but allocated during run time with malloc/calloc.

Dynamic 2D Array Creation in C Language

There are the following ways to dynamically allocate a 2D array in C Language:

Single Pointer

In this method, we simply allocate memory of size M*N dynamically and assign it to the pointer. Even though the memory is linearly allocated, we can use pointer arithmetic to index the 2D array.

Program for 2D Array Creation using Single Pointer in C
#include <stdio.h>
#include <stdlib.h>
int main ()
{
    int r = 3, c = 4;
    int *arr = (int *) malloc (r * c * sizeof (int));
    int i, j, count = 0;
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            *(arr + i * c + j) = ++count;

    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            printf ("%d ", *(arr + i * c + j));
    return 0;
}

Output: 1 2 3 4 5 6 7 8 9 10 11 12 

Pointer to a Pointer (Double Pointer)

To develop a 2D array dynamically, we are required to take a pointer to the pointer variable then one array is required to create and manage multiple rows.

Program for 2D Array Dynamic Creation using Pointer to Pointer in C
#include <stdio.h>
#include <stdlib.h>
int main ()
{
    int r = 3, c = 4, i, j, count;
    int **arr = (int **) malloc (r * sizeof (int *));
    for (i = 0; i < r; i++)
        arr[i] = (int *) malloc (c * sizeof (int));
    
    count = 0;
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            arr[i][j] = ++count;

    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            printf ("%d ", arr[i][j]);
    return 0;
}

Output: 1 2 3 4 5 6 7 8 9 10 11 12 

Dynamic 3D Array Creation in C Language

There are the following ways to dynamically allocate a 3D array in C language:

Single Pointer

In this approach, we simply allocate memory of size M*N*O dynamically and assign it to a pointer. Even though the memory is linearly allocated, we can use pointer arithmetic to index the 3D array.

Program for 3D Array Dynamic Creation using Single Pointer in C
#include<stdio.h>
#include<stdlib.h>
#define M 2
#define N 3
#define O 4
int main ()
{
    int i, j, k;
    int *A = (int *) malloc (M * N * O * sizeof (int));
    if (A == NULL)
    {
        fprintf (stderr, "Out of Memory");
        exit (0);
    }
    for (i = 0; i < M; i++)
        for (j = 0; j < N; j++)
            for (k = 0; k < O; k++)
                *(A + i * N * O + j * O + k) = rand () % 100;

    for (i = 0; i < M; i++)
    {
        for (j = 0; j < N; j++)
        {
            for (k = 0; k < O; k++)
                printf ("%d", *(A + i * N * O + k));
            printf ("\n");
        }
        printf ("\n");
    }
    free (A);
    return 0;
}
Output:
Dynamic Array Creation in C Language with Examples
Triple Pointer:

Implementing multi-dimensional arrays in C is very similar, we use malloc()\free() stdlib methods instead of the new\delete keywords. 

Program for 3D Array Creation using Triple Pointer in C Language
#include <stdio.h>
#include <stdlib.h>
void main ()
{
    int x = 3, y = 4, z = 5;
    int i, j, k;
    int *allElements = malloc (x * y * z * sizeof (int));
    int ***array3D = malloc (x * sizeof (int **));
    for (i = 0; i < x; i++)
    {
        array3D[i] = malloc (y * sizeof (int *));
        for (j = 0; j < y; j++)
        {
            array3D[i][j] = allElements + (i * y * z) + (j * z);
        }
    }

    for (i = 0; i < x; i++)
    {
        printf ("%d\n", i);
        for (j = 0; j < y; j++)
        {
            printf ("\n");
            for (k = 0; k < z; k++)
            {
                array3D[i][j][k] = (i * y * z) + (j * z) + k;
                printf ("\t%d", array3D[i][j][k]);
            }
        }
        printf ("\n\n");
    }
    free (allElements);
    for (i = 0; i < x; i++)
    {
        free (array3D[i]);
    }
    free (array3D);
}
Output:
Dynamic Array Creation in C Programming Language
]]>
4275
Dynamic Memory Management in C Programming https://shishirkant.com/dynamic-memory-management-in-c-programming/?utm_source=rss&utm_medium=rss&utm_campaign=dynamic-memory-management-in-c-programming Mon, 04 Sep 2023 15:22:40 +0000 https://shishirkant.com/?p=4272 Memory Management in C

In the C Programming language, we are having two types of Memory Management

  1. Static Memory Management
  2. Dynamic Memory Management
Static Memory Management in C Language
  1. When we are creating the memory at the time of compilation then it is called static Memory Management or Compile-time Memory Management. Static Memory Allocation is under control of Compiler.
  2. When we are working with Static Memory Allocation, it is not possible to extend the memory at the time of execution, if it is not sufficient.
  3. When we are working with static memory allocation, we need to go for pre-allocation of memory i.e. how many bytes of data required to be created is needed to be decided using coding only.
Static Memory Management in C Language
Dynamic Memory Management in C Language
  1. It is a procedure of allocating or de-allocating the memory at the run time i.e. dynamically. By using Dynamic Memory Allocation, we can utilize the memory more efficiently according to the requirement.
  2. By using dynamic Memory allocation, whenever we want, which type we want, and how much we want, that time, type, and that much we can create dynamically.

Note: Dynamic Memory Allocation related all predefined functions are declared in <malloc.h>, <alloc.h>,<stdio.h>

Dynamic Memory Allocation Related Predefined Functions in C Language:

malloc() function in C:

By using this predefined function, we can create the memory dynamically at initial stage. malloc() function require 1 argument of type size_type i.e., datatype size. malloc() creates memory in bytes format and initial value is garbage.

Syntax: void *malloc(size_type);

Dynamic Memory Allocation related functions can be applied for any datatype that’s why functions return void* i.e. generic type. When we are working with Dynamic Memory Allocation related functions, we are required to perform Type Casting because functions return void*.

Dynamic Memory Management in C Language
Program for Dynamic Memory Allocation using malloc() Function in C Language
#include <stdio.h>
#include <stdlib.h>
int main ()
{
    int *ptr;
    int n, i;
    n = 5;
    printf ("Enter number of elements: %d\n", n);
    ptr = (int *) malloc (n * sizeof (int));
    if (ptr == NULL)
    {
        printf ("Memory not allocated.\n");
        exit (0);
    }
    else
    {
        printf ("Memory successfully allocated using malloc.\n");
        for (i = 0; i < n; ++i)
        {
            ptr[i] = i + 1;
        }
        printf ("The elements of the array are: ");
        for (i = 0; i < n; ++i)
        {
            printf ("%d, ", ptr[i]);
        }
    }
    return 0;
}
Output:
Program for Dynamic Memory Allocation using malloc() Function in C Language
free() function in C Language:

By using this predefined function, we can deallocate dynamically allocated memory. When we are working with Dynamic /memory Allocation related memory, it stores in the heap area of the data segment and it is permanent memory if we are not deallocating. When we are working with Dynamic Memory Allocation related programs, at the end of the program recommended to deallocate memory by using the free() function. free() function requires one argument of type (void*) and returns void type.

Syntax: void free(void *ptr);

Program for Memory Deallocation using the free function in C Language
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
int main ()
{
    int *arr;
    int sum = 0, i, size;
    float avg;
    printf ("\n enter array size:");
    scanf ("%d", &size);
    arr = (int *) malloc (sizeof (int) * size);
    printf ("\n Default Values : ");
    for (i = 0; i < size; i++)
        printf ("%d", arr[i]);
    printf ("\n enter %d values : ", size);
    for (i = 0; i < size; i++)
    {
        scanf ("%d", &arr[i]);
        sum += arr[i];
    }
    avg = (float) sum / size;
    printf ("\n sum of List : %d", sum);
    printf ("\n Avg of List : 5.2f", avg);
    free (arr);
    arr = NULL;
    return 0;
}
Output:
Program for Memory Deallocation using the free function in C Language
Calloc Function in C Language:

By using this predefined function, we can create the memory dynamically at the initial stage. calloc() requires two argument of type (count, size_type). the count will provide a number of elements, size_type is datatype size. when we are working will calloc() function, it creates the memory in block format and the initial value is zero.

Syntax: void *calloc(count, size_type);

Calloc() Function in C Language
Program for Dynamic Memory Allocation using calloc() Function in C Language
#include <stdio.h>
#include <stdlib.h>
int main ()
{
    int *ptr;
    int n, i;
    n = 5;
    printf ("Enter number of elements: %d\n", n);
    ptr = (int *) calloc (n, sizeof (int));
    if (ptr == NULL)
    {
        printf ("Memory not allocated.\n");
        exit (0);
    }
    else
    {
        printf ("Memory successfully allocated using calloc.\n");
        for (i = 0; i < n; ++i)
        {
            ptr[i] = i + 1;
        }
        printf ("The elements of the array are: ");
        for (i = 0; i < n; ++i)
        {
             printf ("%d, ", ptr[i]);
        }
    }
    return 0;
}
Output:
Program for Dynamic Memory Allocation using calloc() Function in C Language
Realloc() Function in C Language:

By using this predefined function, we can create the memory dynamically at the middle stage of the program. Generally, this function is required to use when we are reallocating memory. realloc() requires two arguments of type void*, size_type. void* indicates previous block base address, size_type is datatype size. When we are working with realloc() function, it creates the memory in bytes format and the initial value is garbage.

Syntax: void *realloc(void*, size_type)

Realloc() Function in C Language
Program for Dynamic Memory Allocation using realloc Function in C Language
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
int main ()
{
    int *arr;
    int s1, s2, i;
    printf ("\n Enter array size1:");
    scanf ("%d", &s1);
    arr = (int *) calloc (s1, sizeof (int));
    printf ("\n Enter %d values:", s1);
    for (i = 0; i < s1; i++)
        scanf ("%d", &arr[i]);

    printf ("\n Enter array size2:");
    scanf ("%d", &s2);
    arr = (int *) realloc (arr, sizeof (int) * (s1 + s2));
    printf ("\n Enter %d values", s2);
    for (i = s1; i < s1 + s2; i++)
        scanf ("%d", &arr[i]);

    printf ("\n Array Data List :");
    for (i = 0; i < s1 + s2; i++)
        printf ("%d ", arr[i]);

    printf ("%d", arr[i]);
    free (arr);
    arr = NULL;
    return 0;
}
Output:
Program for Dynamic Memory Allocation using realloc Function in C Language
]]>
4272
Typedef in C Programming https://shishirkant.com/typedef-in-c-programming/?utm_source=rss&utm_medium=rss&utm_campaign=typedef-in-c-programming Mon, 04 Sep 2023 15:13:53 +0000 https://shishirkant.com/?p=4269 Typedef in C Language:

It is a Keyword, by using this keyword, we can create a user-defined name for an existing data type. The typedef is a keyword in the C programming language which is used to provide meaningful names to already existing variables inside a C program. In short, we can say that this typedef keyword is used to redefine the name of an already existing variable.

Syntax: typedef Datatype user_defined_name

Program to understand Typedef in C Language:
#include<stdio.h>
#include<conio.h>
typedef int myint;
int main ()
{
    int x;
    myint y;
    typedef myint smallint;
    smallint z;
    printf ("enter 2 values:");
    scanf ("%d %d", &x, &y);
    z = x + y;
    printf ("sum value is:%d", z);
    getch ();
    return 0;
}
Output:
Program to understand Typedef in C Language
Typedef Example in C:
#include <stdio.h>
#include<conio.h>
#define MYCHAR char;
typedef char BYTE;
int main ()
{
    char ch1 = 'A';
    MYCHAR ch2 = 'b';
    BYTE ch3;
    ch3 = ch2 + ch1 + 20;
    printf ("char1:%c char2:%c char3:%c", ch1, ch2, ch3);
    getch ();
    return 0;
}
Output:
Typedef in C Language with Examples

By using #define, we can’t create alias name because, at the time of pre-processing, the identifier is replaced with the replacement text. #define is under control of pre-processor, typedef is under control of compiler.

]]>
4269