Skip to main content

In this blogging you know about digital world.

Function in C

  Function Function : In C programming, a function is a self-contained block of code that performs a specific task or a set of related tasks. Functions are used to break down a program into smaller, more manageable pieces, making the code more organized, readable, and reusable. C supports various types of functions, including library functions and user-defined functions. Below, I'll describe functions in C with examples and discuss their types. Function Syntax: return_type function_name(parameters) {     // Function body     // Statements to perform a task     return value; // (optional) Return value } Here's a breakdown of the elements: - `return_type`: Specifies the data type of the value the function returns. Use `void` if the function doesn't return anything. - `function_name`: A unique identifier for the function. - `parameters`: Input values that the function can accept (optional). - `function_body`: Conta...

Pointer

Pointer

In C, a pointer is a variable that is used to store the memory address of another variable. Pointers are a fundamental concept in C and are often used for various purposes, such as dynamic memory allocation, passing arguments to functions by reference, and working with complex data structures like arrays and linked lists.

Here's a basic description of pointers in C along with an example:

1. Declaration of Pointers:

   To declare a pointer variable, you use an asterisk (*) before the variable name. For example:

            int *ptr; // Declares a pointer to an integer

   This declaration creates a pointer called `ptr` that can store the memory address of an integer variable.

 

2. Assigning Addresses to Pointers:

   You can assign the address of a variable to a pointer using the address-of operator (&). For example:

             int x = 10;  // Declare an integer variable

            int *ptr;    // Declare a pointer to an integer

            ptr = &x;    // Assign the address of x to ptr

   Now, `ptr` points to the memory location where the integer variable `x` is stored.

 

3. Accessing the Value Pointed to by a Pointer:

   You can access the value stored at the memory address pointed to by a pointer using the dereference operator (*). For example:

            int y = *ptr; // Assigns the value at the memory location pointed by ptr to y

  In this case, `y` will be assigned the value 10 because `ptr` points to the memory location of `x`, which contains 10.

Here's a complete example that demonstrates these concepts:

#include <stdio.h>

int main() {

    int x = 10;  // Declare an integer variable

    int *ptr;    // Declare a pointer to an integer

    ptr = &x;    // Assign the address of x to ptr

    // Access and modify the value pointed to by ptr

    *ptr = 20;

    printf("The value of x: %d\n", x);   // Should print 20

    printf("The value pointed to by ptr: %d\n", *ptr); // Should print 20

    return 0;

}

In this example, we declare an integer variable `x`, a pointer to an integer `ptr`, and assign the address of `x` to `ptr`. We then use the pointer to modify the value of `x`, and both `x` and the value pointed to by `ptr` become 20.

Pointers in C are powerful and flexible but require careful use to avoid issues like segmentation faults and memory leaks. Proper understanding and management of memory allocation and deallocation are crucial when working with pointers in C.

How To Use Pointer: -

Pointers in C are powerful and fundamental features that allow you to work with memory addresses, providing you with fine-grained control over memory management. They are often used for tasks such as dynamic memory allocation, array manipulation, and creating data structures like linked lists and trees. Here's an overview of how to use pointers in C:

1. Declaration and Initialization:

   - Declare a pointer using the `*` operator. For example:

     int *ptr;

   - Initialize a pointer with the address of a variable using the `&` operator:

     int num = 42;

     int *ptr = &num;

 

2. Dereferencing:

   - To access the value stored at the memory address pointed to by a pointer, use the `*` operator:

     int value = *ptr;

   

3. Pointer Arithmetic:

   - Pointers can be incremented or decremented to move through memory:

     ptr++; // Moves to the next memory location.

     ptr--; // Moves to the previous memory location.

 

4. Dynamic Memory Allocation:

   - Use pointers for dynamic memory allocation with functions like `malloc`, `calloc`, and `realloc` from the `<stdlib.h>` library:

     int *arr = (int *)malloc(sizeof(int) * 5);

 

5. Arrays and Pointers:

   - Arrays are closely related to pointers. An array name can be used as a pointer to its first element:

     int arr[5] = {1, 2, 3, 4, 5};

     int *ptr = arr; // ptr points to the first element of arr

    

 

6. Function Pointers:

   - You can declare and use pointers to functions. This is useful for implementing callbacks and dynamic function selection:

     int (*add)(int, int);

     add = &sum; // assuming 'sum' is a function

     int result = add(5, 3); // calls the 'sum' function

    

7. Passing Pointers to Functions:

   - Pointers are often used to pass data to functions by reference. This allows functions to modify the original data:

     void modifyValue(int *ptr) {

         (*ptr) += 10;

     }

  

8. Pointer to Structures:

   - You can use pointers to access and manipulate members of a structure:

     struct Point {

         int x;

         int y;

     };

     struct Point p;

     struct Point *ptr = &p;

     ptr->x = 5; // Accessing the 'x' member through a pointer

    

9. Pointers and Strings:

   - C-style strings are essentially arrays of characters, and you often use pointers to manipulate them:

     char *str = "Hello, World!";

     printf("%s", str);

    

10. Null Pointers:

    - Initialize pointers to `NULL` when they don't point to valid memory locations to avoid undefined behavior:

      int *ptr = NULL;

     

11. Pointer Safety:

    - Be very careful with pointers to avoid memory leaks, buffer overflows, and segmentation faults. Always check if a pointer is valid before using it.

Remember that pointer manipulation in C requires a good understanding of memory management and can lead to bugs like memory leaks or segmentation faults if not used correctly. Use them judiciously and consider safer alternatives like smart pointers or array bounds checking in modern languages like C++ or Rust for certain tasks.

Pointer in C Example

// C program to illustrate Pointers

#include <stdio.h>

void geeks()

{

            int var = 10;

            // declare pointer variable

            int* ptr;

            // note that data type of ptr and var must be same

            ptr = &var;

            // assign the address of a variable to a pointer

            printf("Value at ptr = %p \n", ptr);

            printf("Value at var = %d \n", var);

            printf("Value at *ptr = %d \n", *ptr);

}

// Driver program

int main()

{

            geeks();

            return 0;

}

Here are some common types of pointers:

1. Null Pointer:

   - A null pointer does not point to any memory location.

   - It's often used to indicate that a pointer does not currently reference any valid data.

      int* nullPointer = NULL; // or int* nullPointer = 0;

 

2. Void Pointer (or Generic Pointer):

   - A void pointer is a pointer that doesn't have a specific data type associated with it.

   - It's often used when the type of data the pointer will point to is unknown.

   void* genericPointer;

   int x = 10;

   genericPointer = &x;

 

3. Pointer to Integer:

   - A pointer that stores the memory address of an integer variable.

   int* intPointer;

   int x = 10;

   intPointer = &x;

  

4. Pointer to Character (Char Pointer):

   - A pointer that stores the memory address of a character variable (char).

   char* charPointer;

   char c = 'A';

   charPointer = &c;

 

5. Pointer to Array:

   - A pointer that points to the first element of an array.

   int arr[5] = {1, 2, 3, 4, 5};

   int* arrPointer = arr;

  

6. Pointer to Function:

   - A pointer that stores the memory address of a function.

   int (*functionPointer)(int, int);

   int add(int a, int b) {

       return a + b;

   }

   functionPointer = add;

 

7. Pointer to Pointer (Double Pointer):

   - A pointer that stores the memory address of another pointer.

   int x = 10;

   int* intPointer = &x;

   int doublePointer = &intPointer;

 

8. Pointer to Structure (Struct Pointer):

   - A pointer that points to a structure (or a record in some programming languages).

struct Point {

       int x;

       int y;

   };

   struct Point point = {5, 10};

   struct Point* structPointer = &point;

 

9. Pointer to Union (Union Pointer):

   - A pointer that points to a union. Unions are similar to structures but share the same memory location for all their members. 

   union Data {

       int i;

       float f;

   };

   union Data data;

   data.i = 42;

   union Data* unionPointer = &data;

These are some common types of pointers in programming. The choice of pointer type depends on the specific use case and the type of data you are working with.

Other Types of Pointers in C:

Far pointer: A far pointer is typically 32-bit that can access memory outside the current segment.

Dangling pointer: A pointer pointing to a memory location that has been deleted (or freed) is called a dangling pointer.

Huge pointer: A huge pointer is 32-bit long containing segment address and offset address.

Complex pointer: Pointers with multiple levels of indirection.

Near pointer: Near pointer is used to store 16-bit addresses means within the current segment on a 16-bit machine.

Normalized pointer: It is a 32-bit pointer, which has as much of its value in the segment register as possible.

File Pointer: The pointer to a FILE data type is called a stream pointer or a file pointer.

 

Size of Pointers in C

The size of the pointers in C is equal for every pointer type. The size of the pointer does not depend on the type it is pointing to. It only depends on the operating system and CPU architecture. The size of pointers in C is

8 bytes for a 64-bit System

4 bytes for a 32-bit System

The reason for the same size is that the pointers store the memory addresses, no matter what type they are. As the space required to store the addresses of the different memory locations is the same, the memory required by one pointer type will be equal to the memory required by other pointer types.

 

How to find the size of pointers in C?

We can find the size of pointers using the sizeof operator as shown in the following program:

Example: C Program to find the size of different pointer types.

 

// C Program to find the size of different pointers types

#include <stdio.h>

// dummy structure

struct str {

};

// dummy function

void func(int a, int b){};

int main()

{

            // dummy variables definitions

            int a = 10;

            char c = 'G';

            struct str x;

            // pointer definitions of different types

            int* ptr_int = &a;

            char* ptr_char = &c;

            struct str* ptr_str = &x;

            void (*ptr_func)(int, int) = &func;

            void* ptr_vn = NULL;

            // printing sizes

            printf("Size of Integer Pointer \t:\t%d bytes\n",

                        sizeof(ptr_int));

            printf("Size of Character Pointer\t:\t%d bytes\n",

                        sizeof(ptr_char));

            printf("Size of Structure Pointer\t:\t%d bytes\n",

                        sizeof(ptr_str));

            printf("Size of Function Pointer\t:\t%d bytes\n",

                        sizeof(ptr_func));

            printf("Size of NULL Void Pointer\t:\t%d bytes",

                        sizeof(ptr_vn));

            return 0;

}

Output

Size of Integer Pointer      :    8 bytes

Size of Character Pointer    :    8 bytes

Size of Structure Pointer    :    8 bytes

Size of Function Pointer    :    8 bytes

Size of NULL Void Pointer    :    8 bytes

As we can see, no matter what the type of pointer it is, the size of each and every pointer is the same.

Now, one may wonder that if the size of all the pointers is the same, then why do we need to declare the pointer type in the declaration? The type declaration is needed in the pointer for dereferencing and pointer arithmetic purposes.

 

Pointer Arithmetic

The Pointer Arithmetic refers to the legal or valid arithmetic operations that can be performed on a pointer. It is slightly different from the ones that we generally use for mathematical calculations as only a limited set of operations can be performed on pointers. These operations include:

Increment in a Pointer

Decrement in a Pointer

Addition of integer to a pointer

Subtraction of integer to a pointer

Subtracting two pointers of the same type

Comparison of pointers of the same type.

Assignment of pointers of the same type.

 

// C program to illustrate Pointer Arithmetic

#include <stdio.h>

 

int main()

{

            // Declare an array

            int v[3] = { 10, 100, 200 };

            // Declare pointer variable

            int* ptr;

            // Assign the address of v[0] to ptr

            ptr = v;

            for (int i = 0; i < 3; i++) {

                        // print value at address which is stored in ptr

                        printf("Value of *ptr = %d\n", *ptr);

                        // print value of ptr

                        printf("Value of ptr = %p\n\n", ptr);

                        // Increment pointer ptr by 1

                        ptr++;

            }

            return 0;

}

Comments

Popular Posts