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›Arrays: Defining Arrays, Character Arrays, Static and Automatic Local Arrays
    Programming FundamentalsTopic 18 of 39

    Arrays: Defining Arrays, Character Arrays, Static and Automatic Local Arrays

    7 minread
    1,170words
    Intermediatelevel

    Arrays in C: Defining Arrays, Character Arrays, Static and Automatic Local Arrays

    In C, arrays are a fundamental data structure used to store multiple values of the same type in a contiguous memory block. They allow for easy access and manipulation of a collection of related data. Understanding how arrays work and the different types of arrays, such as character arrays and static vs automatic local arrays, is essential for efficient programming in C.

    Let’s break down the key concepts of arrays in C.


    1. Defining Arrays in C

    An array in C is defined by specifying the type of elements it will store, followed by the name of the array, and the number of elements it can hold (its size).

    Syntax:

    type arrayName[arraySize];
    
    • type: The data type of the elements (e.g., int, float, char).
    • arrayName: The name of the array.
    • arraySize: The number of elements the array can hold (the size of the array).

    Example: Defining an Integer Array

    #include <stdio.h>
    
    int main() {
        // Define an array of 5 integers
        int numbers[5] = {1, 2, 3, 4, 5};
    
        // Access and print array elements
        for (int i = 0; i < 5; i++) {
            printf("numbers[%d] = %d\n", i, numbers[i]);
        }
    
        return 0;
    }
    

    Explanation:

    • An array numbers of size 5 is defined.
    • The elements of the array are initialized with values {1, 2, 3, 4, 5}.
    • We then loop through the array to print each element.

    Output:

    numbers[0] = 1
    numbers[1] = 2
    numbers[2] = 3
    numbers[3] = 4
    numbers[4] = 5
    

    2. Character Arrays

    In C, a character array is a special kind of array used to store strings. Since strings in C are represented as arrays of characters, a character array is used to hold a sequence of characters, with the last character always being a null terminator ('\0').

    Defining a Character Array:

    A string can be defined by initializing a character array with a string literal, which is automatically terminated by a null character.

    Syntax:

    char stringName[arraySize];
    

    Alternatively, you can define the array as:

    char stringName[] = "Hello";
    
    • In this case, the compiler will automatically determine the array size based on the length of the string, including the null terminator.

    Example: Defining and Printing a String Using a Character Array

    #include <stdio.h>
    
    int main() {
        // Define a character array (string)
        char name[] = "John";
    
        // Print the string
        printf("Hello, %s!\n", name);
    
        return 0;
    }
    

    Explanation:

    • The string "John" is stored in a character array name. In memory, it will look like this: {'J', 'o', 'h', 'n', '\0'}.
    • The %s format specifier is used in printf to print the string (i.e., the characters up to the null terminator).

    Output:

    Hello, John!
    

    Important Note:

    • If you define a character array large enough to hold a string, make sure it is always null-terminated, as C relies on the null terminator to identify the end of a string. For example, a string "Hello" requires an array of at least 6 characters (5 characters for "Hello" and 1 for '\0').

    3. Static and Automatic Local Arrays

    In C, arrays can be declared as static or automatic local arrays, which determines their lifetime, memory allocation, and scope.

    Automatic Local Arrays:

    • Automatic arrays are the default type of local arrays in C. These arrays are created when the function they are declared in is called and are destroyed when the function exits.
    • They are stored on the stack and have a limited scope (accessible only within the function or block where they are declared).
    Key Characteristics:
    • Memory is automatically allocated and deallocated when the function is called and returns.
    • The values stored in the array are not retained between function calls (they are not persistent).
    Example: Automatic Local Array
    #include <stdio.h>
    
    void printNumbers() {
        int numbers[3] = {1, 2, 3};  // Automatic array
    
        for (int i = 0; i < 3; i++) {
            printf("numbers[%d] = %d\n", i, numbers[i]);
        }
    }
    
    int main() {
        printNumbers();  // Call function with automatic array
    
        return 0;
    }
    

    Static Local Arrays:

    • A static array in C retains its value even after the function returns. It is initialized only once and persists across function calls. Static arrays are stored in the data segment of memory, not on the stack.
    • Static arrays are declared using the static keyword.
    Key Characteristics:
    • Memory is allocated once when the program starts and is released when the program ends.
    • The values stored in a static array persist between function calls, unlike automatic arrays.
    Example: Static Local Array
    #include <stdio.h>
    
    void printNumbers() {
        static int numbers[3] = {1, 2, 3};  // Static array
    
        // Modify the array value
        numbers[0] += 10;
    
        for (int i = 0; i < 3; i++) {
            printf("numbers[%d] = %d\n", i, numbers[i]);
        }
    }
    
    int main() {
        printNumbers();  // First call
        printNumbers();  // Second call
    
        return 0;
    }
    

    Explanation:

    • The first time printNumbers() is called, the array is initialized with {1, 2, 3}.
    • The second time printNumbers() is called, the array retains its previous state (numbers[0] = 11), because it is a static array.
    • The array's values are retained between function calls.

    Output:

    numbers[0] = 11
    numbers[1] = 2
    numbers[2] = 3
    numbers[0] = 11
    numbers[1] = 2
    numbers[2] = 3
    

    Comparison Between Static and Automatic Local Arrays

    Feature Automatic Local Arrays Static Local Arrays
    Memory Allocation Allocated and deallocated when the function is called and returns. Allocated once when the program starts and persists throughout the program.
    Lifetime Only exists while the function is executing. Exists for the lifetime of the program.
    Initialization Initialized every time the function is called. Initialized only once, the first time the function is called.
    Persistence Between Calls Values are lost after the function exits. Values persist between function calls.

    4. Summary of Key Concepts

    1. Defining Arrays:

      • Arrays are defined by specifying the data type, name, and size.
      • Arrays store multiple values of the same data type in contiguous memory locations.
    2. Character Arrays:

      • Character arrays are used to store strings.
      • Strings are arrays of characters that are null-terminated ('\0').
    3. Automatic Local Arrays:

      • These arrays are created when a function is called and destroyed when it returns.
      • The values are not retained between function calls.
    4. Static Local Arrays:

      • Static arrays retain their values between function calls and persist throughout the program's lifetime.
      • They are initialized only once and can be accessed across multiple calls to the function.

    Understanding these array types helps manage memory effectively and allows for better organization of data in your programs.

    Previous topic 17
    Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration
    Next topic 19
    Passing Arrays to Function, Sorting and Searching Arrays

    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,170
      Code examples0
      DifficultyIntermediate