ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCC-112Pointer Arithmetic Arr…
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CC-112

    Programming Fundamentals

    Progress0 / 39 done
    Topics39
    1Introduction to Problem Solving, Algorithms, Programming, and C Language2Problem Solving, a brief review of Von-Neumann Architecture3The C Programming Language, Pseudo-code, Concept of Variable4Data types in Pseudo-code, The C Standard Library and Open Source5Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6Concept of Integer division, Flowchart and its notations7Typical C Program Development Environment, Role of Compiler and Linker8Test Driving C Application
    9A Simple C Program: Printing Text, Adding Two Integer10Memory Concepts, Arithmetic in C, Operators
    11Equality and Relational Operators
    12The if, if...else, while Nested Control Statements
    13for, switch, do...while, break, continue, Logical Operators
    14Modularizing Program in C, Math Library Functions15Function Definitions and Prototypes, Function-Call Stack and Stack Frames16Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration
    18Defining Arrays, Character Arrays, Static and Automatic Local Arrays19Passing Arrays to Function, Sorting and Searching Arrays20Multidimensional and Variable Length Arrays
    21Pointer Definitions and Initialization, Pointer Operators22Passing Arguments to Function by Reference, Using the const and sizeof Operator23Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24Function Pointers
    25Strings and Characters, Character Handling Library26String Functions, Library Functions
    27Streams, Formatted Output with printf, Formatted Input with scanf
    28Defining Structures, Accessing Structure Member, Structures and Functions29typedef, Unions
    30Bitwise Operators, Bit Fields, Enumeration Constants
    31Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File
    32#include, #define, Conditional Compilation, #error and #pragma33# and ## Operators, Predefined Symbolic Constants, Assertions
    34Variable Length Argument List, Using Command Line Arguments35Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36Suffixes for Integer and Floating-Point Literals, Signal Handling
    37calloc and realloc, goto
    38Self-Referential Structures, Linked Lists39Efficiency of Algorithms, Selection and Insertion Sort
    7 min read
    Topic 23 of 39
    Topic Study Note Illustration
    23

    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 ,...

    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 view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    7mremaining
    1.2kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Programming Fundamentals