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›Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers
    Programming FundamentalsTopic 23 of 39

    Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers

    7 minread
    1,249words
    Intermediatelevel

    Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers

    Pointers are a fundamental concept in C programming, allowing for powerful manipulation of memory addresses. Understanding pointer expressions and arithmetic, how pointers relate to arrays, and working with arrays of pointers is crucial for writing efficient C code. Let’s break these topics down in detail.


    1. Pointer Expressions and Arithmetic

    C allows pointer arithmetic which enables manipulation of pointer values in arithmetic terms. This is possible because pointers in C are associated with specific memory addresses, and you can increment or decrement the pointer based on the type of data they point to.

    Pointer Arithmetic Overview

    • Increment (ptr++): Moves the pointer to the next memory location of the data type it points to.
    • Decrement (ptr--): Moves the pointer to the previous memory location of the data type it points to.
    • Addition (ptr + n): Moves the pointer n positions forward, where each position corresponds to the size of the data type the pointer is pointing to.
    • Subtraction (ptr - n): Moves the pointer n positions backward.
    • Pointer Difference (ptr1 - ptr2): Finds the difference between two pointers, which tells how many elements are between the two pointers.

    Pointer Arithmetic Example

    #include <stdio.h>
    
    int main() {
        int arr[] = {10, 20, 30, 40, 50};
        int *ptr = arr;
    
        printf("Value at ptr: %d\n", *ptr);  // Prints 10 (first element)
        ptr++;  // Increment pointer, now points to second element
        printf("Value at ptr after ptr++: %d\n", *ptr);  // Prints 20
    
        ptr += 2;  // Move pointer 2 steps ahead
        printf("Value at ptr after ptr += 2: %d\n", *ptr);  // Prints 40
    
        ptr--;  // Decrement pointer, now points to third element
        printf("Value at ptr after ptr--: %d\n", *ptr);  // Prints 30
    
        return 0;
    }
    

    Explanation:

    • Initially, the pointer ptr points to the first element of the array (arr[0]).
    • Using ptr++, the pointer moves to the next memory location, which is the second element in the array (arr[1]).
    • ptr += 2 moves the pointer two elements ahead, making it point to arr[3].
    • The pointer can be moved back with ptr--, bringing it to point to arr[2].

    Output:

    Value at ptr: 10
    Value at ptr after ptr++: 20
    Value at ptr after ptr += 2: 40
    Value at ptr after ptr--: 30
    

    Here, pointer arithmetic allows for easy traversal through the array without needing to use array indices.


    2. Pointers and Arrays

    Arrays and pointers are closely related in C. In fact, the name of an array is essentially a pointer to its first element. Let’s dive into how pointers work with arrays.

    Arrays and Pointers

    • When you declare an array, the name of the array is a pointer to the first element of the array.
    • Array indexing is simply syntactic sugar for pointer arithmetic.

    For example:

    int arr[] = {10, 20, 30, 40, 50};
    int *ptr = arr;  // Equivalent to: int *ptr = &arr[0];
    

    Here, arr is equivalent to &arr[0], which means ptr is pointing to the first element of arr.

    Array Access via Pointer Arithmetic

    You can access array elements using pointers, much like array indexing, but with pointer arithmetic.

    #include <stdio.h>
    
    int main() {
        int arr[] = {10, 20, 30, 40, 50};
        int *ptr = arr;  // Pointer to the first element of the array
    
        // Access elements using pointer arithmetic
        printf("First element: %d\n", *ptr);      // Access arr[0]
        printf("Second element: %d\n", *(ptr + 1));  // Access arr[1]
        printf("Fourth element: %d\n", *(ptr + 3));  // Access arr[3]
    
        return 0;
    }
    

    Explanation:

    • *ptr gives you the value of arr[0].
    • *(ptr + 1) gives you the value of arr[1], as ptr + 1 points to the second element of the array.
    • This is the equivalent of using array indices, but it demonstrates the underlying pointer arithmetic.

    Output:

    First element: 10
    Second element: 20
    Fourth element: 40
    

    Here, the pointer ptr is used to access array elements through pointer arithmetic. This is often more efficient when working with large arrays or when memory addresses are needed.


    3. Array of Pointers

    An array of pointers is a collection of pointers, where each pointer in the array can point to a different data element (usually of the same type). This is useful when working with dynamic memory allocation or handling strings.

    Array of Pointers Example

    Consider an array of strings (each string is a pointer to a character array):

    #include <stdio.h>
    
    int main() {
        char *fruits[] = {"Apple", "Banana", "Cherry", "Date", "Elderberry"};
        
        // Loop through array of pointers and print each string
        for (int i = 0; i < 5; i++) {
            printf("%s\n", fruits[i]);
        }
    
        return 0;
    }
    

    Explanation:

    • fruits[] is an array of pointers, where each element in the array is a pointer to a string (character array).
    • Each string literal ("Apple", "Banana", etc.) is a pointer to the first character of the string.
    • The loop iterates over the array of pointers and prints each string.

    Output:

    Apple
    Banana
    Cherry
    Date
    Elderberry
    

    In this case, fruits is an array of pointers to strings, and each pointer points to the first character of the respective string.

    Another Example: Array of Function Pointers

    You can also create an array of function pointers, which is useful for implementing callback functions or for managing multiple functions that perform similar tasks.

    #include <stdio.h>
    
    void add(int a, int b) {
        printf("%d + %d = %d\n", a, b, a + b);
    }
    
    void multiply(int a, int b) {
        printf("%d * %d = %d\n", a, b, a * b);
    }
    
    int main() {
        // Array of function pointers
        void (*operations[2])(int, int) = {add, multiply};
    
        // Calling functions via pointers
        operations[0](5, 3);  // Calls add
        operations[1](5, 3);  // Calls multiply
    
        return 0;
    }
    

    Explanation:

    • The array operations[] holds pointers to functions that take two int arguments and return void.
    • We can call add and multiply functions using the array of function pointers.

    Output:

    5 + 3 = 8
    5 * 3 = 15
    

    Here, the array operations[] is used to store function pointers, allowing dynamic function calls at runtime.


    4. Summary of Key Concepts

    • Pointer Arithmetic: C allows pointer arithmetic, which enables moving pointers through memory locations by incrementing, decrementing, or adding/subtracting based on the size of the type the pointer points to.
    • Pointers and Arrays: The name of an array is a pointer to its first element. You can access array elements through pointers and pointer arithmetic.
    • Array of Pointers: An array of pointers stores multiple pointers, allowing each pointer to reference different variables or data types. This is particularly useful for arrays of strings, dynamic memory allocation, or managing function pointers.

    Understanding pointer expressions, arithmetic, and the relationship between pointers and arrays is essential for effective memory manipulation, working with dynamic data structures, and optimizing performance in C programming.

    Previous topic 22
    Passing Arguments to Function by Reference, Using the const and sizeof Operator
    Next topic 24
    Function Pointers

    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 time7 min
      Word count1,249
      Code examples0
      DifficultyIntermediate