ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Programming Fundamentals
    CC-112
    Progress0 / 39 topics
    Topics
    1. Introduction to Problem Solving, Algorithms, Programming, and C Language2. Problem Solving, a brief review of Von-Neumann Architecture3. The C Programming Language, Pseudo-code, Concept of Variable4. Data types in Pseudo-code, The C Standard Library and Open Source5. Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6. Concept of Integer division, Flowchart and its notations7. Typical C Program Development Environment, Role of Compiler and Linker8. Test Driving C Application9. Introduction to C Programming: A Simple C Program: Printing Text, Adding Two Integer10. Memory Concepts, Arithmetic in C, Operators11. Decision Making: Equality and Relational Operators12. Structured Program Development: The if, if...else, while Nested Control Statements13. Program Control: for, switch, do...while, break, continue, Logical Operators14. Functions: Modularizing Program in C, Math Library Functions15. Function Definitions and Prototypes, Function-Call Stack and Stack Frames16. Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17. Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration18. Arrays: Defining Arrays, Character Arrays, Static and Automatic Local Arrays19. Passing Arrays to Function, Sorting and Searching Arrays20. Multidimensional and Variable Length Arrays21. Pointers: Pointer Definitions and Initialization, Pointer Operators22. Passing Arguments to Function by Reference, Using the const and sizeof Operator23. Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24. Function Pointers25. Characters and Strings: Strings and Characters, Character Handling Library26. String Functions, Library Functions27. Formatted Input/Output: Streams, Formatted Output with printf, Formatted Input with scanf28. Structures: Defining Structures, Accessing Structure Member, Structures and Functions29. typedef, Unions30. Bit Manipulation and Enumeration: Bitwise Operators, Bit Fields, Enumeration Constants31. File Processing: Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File32. Preprocessor: #include, #define, Conditional Compilation, #error and #pragma33. # and ## Operators, Predefined Symbolic Constants, Assertions34. Other Topics: Variable Length Argument List, Using Command Line Arguments35. Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36. Suffixes for Integer and Floating-Point Literals, Signal Handling37. Dynamic Memory Allocation: calloc and realloc, goto38. Advance Topics: Self-Referential Structures, Linked Lists39. Efficiency of Algorithms, Selection and Insertion Sort
    CC-112›Pointers: Pointer Definitions and Initialization, Pointer Operators
    Programming FundamentalsTopic 21 of 39

    Pointers: Pointer Definitions and Initialization, Pointer Operators

    8 minread
    1,340words
    Intermediatelevel

    Pointers in C: Definitions, Initialization, and Pointer Operators

    In C programming, pointers are variables that store the memory address of another variable. Pointers are a powerful feature in C, allowing for efficient memory management, dynamic memory allocation, and the ability to directly access and modify variables through their memory addresses.

    Let’s explore pointers, their definitions, initialization, and pointer operators in detail.


    1. Pointer Definitions and Initialization

    What is a Pointer?

    A pointer is a variable that holds the memory address of another variable. Instead of storing data directly, it stores the location where the data is located in memory.

    Declaring a Pointer

    To declare a pointer, you use the asterisk (*) symbol. The syntax for declaring a pointer is:

    type *pointerName;
    
    • type: The data type of the variable the pointer will point to.
    • pointerName: The name of the pointer.

    For example:

    int *ptr;  // Pointer to an integer
    char *chPtr;  // Pointer to a character
    

    Here, ptr is a pointer that will hold the memory address of an integer, and chPtr is a pointer that will hold the memory address of a character.

    Initializing a Pointer

    To initialize a pointer, you assign it the address of a variable using the address-of operator (&). For example:

    int x = 10;
    int *ptr = &x;  // ptr now holds the memory address of x
    

    In this case:

    • &x gives the memory address of the variable x.
    • The pointer ptr now points to x.

    Example: Pointer Definition and Initialization

    #include <stdio.h>
    
    int main() {
        int a = 5;
        int *ptr = &a;  // Pointer initialization with the address of variable 'a'
    
        printf("Value of a: %d\n", a);            // Direct access to 'a'
        printf("Address of a: %p\n", &a);         // Address of 'a'
        printf("Pointer ptr points to value: %d\n", *ptr);  // Access value via pointer
        printf("Pointer ptr holds address: %p\n", ptr);  // Address held by pointer
    
        return 0;
    }
    

    Explanation:

    • ptr is initialized to the address of a using &a.
    • *ptr is used to dereference the pointer, accessing the value stored at the address that ptr is pointing to.
    • %p is the format specifier used to print addresses in C.

    Output:

    Value of a: 5
    Address of a: 0x7ffee24b3b8c
    Pointer ptr points to value: 5
    Pointer ptr holds address: 0x7ffee24b3b8c
    

    In this example:

    • The pointer ptr holds the address of a.
    • Dereferencing the pointer using *ptr gives the value of a (which is 5).

    2. Pointer Operators in C

    Pointers are manipulated using a set of operators that are specifically designed for working with memory addresses and the data at those addresses.

    Address-of Operator (&)

    The address-of operator (&) is used to get the memory address of a variable. It is commonly used when initializing a pointer.

    int x = 5;
    int *ptr = &x;  // ptr now holds the address of x
    
    • &x returns the memory address of the variable x.

    Dereference Operator (*)

    The dereference operator (*) is used to access the value stored at the memory address that the pointer is pointing to. It is also used during pointer initialization to declare the type of data that the pointer will point to.

    int x = 10;
    int *ptr = &x;  // Pointer initialized with the address of x
    int value = *ptr;  // Dereferencing the pointer to get the value of x
    
    • *ptr accesses the value of x (which is 10 in this case).

    Example: Using & and * Operators

    #include <stdio.h>
    
    int main() {
        int a = 20;
        int *ptr = &a;  // Pointer ptr holds the address of a
    
        printf("Address of a: %p\n", &a);   // Print address of a
        printf("Pointer ptr points to address: %p\n", ptr);   // Print address held by ptr
        printf("Value of a through pointer: %d\n", *ptr);  // Dereference ptr to get value
    
        *ptr = 30;  // Change value of a through the pointer
        printf("New value of a: %d\n", a);  // Print updated value of a
    
        return 0;
    }
    

    Explanation:

    • &a gives the memory address of a.
    • ptr holds the address of a.
    • *ptr accesses the value stored at the address that ptr is pointing to.
    • By dereferencing ptr (*ptr), you can modify the value of a indirectly.

    Output:

    Address of a: 0x7ffee6a53a0c
    Pointer ptr points to address: 0x7ffee6a53a0c
    Value of a through pointer: 20
    New value of a: 30
    

    In this case:

    • The address of a is printed using &a.
    • The value of a is accessed indirectly via the pointer ptr using *ptr.
    • The value of a is modified through the pointer.

    3. Pointer Arithmetic

    C allows pointer arithmetic, meaning you can perform operations on pointers. These operations are based on the size of the data type the pointer is pointing to. For example, adding 1 to an integer pointer moves the pointer to the next integer in memory.

    Pointer Arithmetic Operations:

    • Increment (ptr++): Move the pointer to the next memory location of the type it points to.
    • Decrement (ptr--): Move the pointer to the previous memory location of the type it points to.
    • Addition (ptr + n): Move the pointer by n elements forward.
    • Subtraction (ptr - n): Move the pointer by n elements backward.
    • Difference between two pointers (ptr1 - ptr2): Calculate the number of elements between two pointers.

    Example: Pointer Arithmetic

    #include <stdio.h>
    
    int main() {
        int arr[] = {10, 20, 30, 40, 50};
        int *ptr = arr;  // Pointer to the first element of arr
    
        // Pointer arithmetic
        printf("First value: %d\n", *ptr);  // 10
        ptr++;  // Move to the next element
        printf("Second value: %d\n", *ptr);  // 20
        ptr += 2;  // Move 2 elements ahead
        printf("Fourth value: %d\n", *ptr);  // 40
        ptr--;  // Move back 1 element
        printf("Third value: %d\n", *ptr);  // 30
    
        return 0;
    }
    

    Explanation:

    • The pointer ptr initially points to the first element of the array arr.
    • Using ptr++, the pointer moves to the next element, and ptr += 2 moves it two elements ahead.
    • Dereferencing the pointer with *ptr gives the value stored at that address.

    Output:

    First value: 10
    Second value: 20
    Fourth value: 40
    Third value: 30
    

    In this example:

    • Pointer arithmetic allows us to access different elements of the array using the pointer ptr.

    4. NULL Pointer

    A NULL pointer is a pointer that does not point to any valid memory location. It is often used to indicate that the pointer is not currently pointing to any object or data.

    You can initialize a pointer to NULL using:

    int *ptr = NULL;
    

    Checking for NULL Pointer

    Before dereferencing a pointer, it is a good practice to check whether it is NULL to avoid runtime errors such as segmentation faults.

    if (ptr != NULL) {
        // Safe to dereference the pointer
        printf("Value: %d\n", *ptr);
    } else {
        printf("Pointer is NULL, cannot dereference.\n");
    }
    

    5. Summary of Key Concepts

    • Pointers are variables that store memory addresses of other variables.
    • The address-of operator (&) is used to get the address of a variable, while the dereference operator (*) is used to access or modify the value stored at that address.
    • Pointer arithmetic allows pointers to be incremented or decremented, which is particularly useful when dealing with arrays.
    • NULL pointers are pointers that do not point to any valid memory and should be checked before dereferencing to avoid errors.

    Pointers are a fundamental part of C programming, enabling efficient memory management, direct memory access, and advanced data structures.

    Previous topic 20
    Multidimensional and Variable Length Arrays
    Next topic 22
    Passing Arguments to Function by Reference, Using the const and sizeof Operator

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time8 min
      Word count1,340
      Code examples0
      DifficultyIntermediate