C Language Syllabus

C Language Concepts

Vectors (Dynamic Arrays)

Definition: In C, vectors or dynamic arrays are arrays whose size can change during runtime using dynamic memory allocation (malloc, realloc).

Example:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr;
    int size = 5;
    arr = (int*)malloc(size * sizeof(int)); // Dynamically allocate array of 5 integers
    
    for (int i = 0; i < size; i++) {
        arr[i] = i + 1;
        printf("%d ", arr[i]);
    }

    // Reallocate memory for more elements
    size = 10;
    arr = (int*)realloc(arr, size * sizeof(int));

    for (int i = 5; i < size; i++) {
        arr[i] = i + 1;
        printf("%d ", arr[i]);
    }

    free(arr); // Free allocated memory
    return 0;
}

Pointers

Definition: Pointers are variables that store the memory address of another variable. They are powerful for handling memory, arrays, and functions efficiently.

Example:

#include <stdio.h>

int main() {
    int x = 10;
    int *p = &x; // p points to the memory address of x
    
    printf("Value of x: %d\n", x);
    printf("Pointer p points to value: %d\n", *p); // Dereference pointer to get the value
    return 0;
}

Types of Pointers

Null Pointers: Points to nothing.

Void Pointers: Generic pointers that can point to any data type.

Function Pointers: Used to point to functions in memory.

Example:

#include <stdio.h>

void hello() {
    printf("Hello, World!\n");
}

int main() {
    void (*funcPtr)() = &hello; // Function pointer
    funcPtr(); // Call function using pointer
    return 0;
}

Memory Allocation

Definition: Memory can be allocated at runtime using functions like malloc, calloc, and realloc. Deallocation is done using free.

Example:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *ptr;
    ptr = (int*)malloc(5 * sizeof(int)); // Allocate memory for 5 integers

    if (ptr == NULL) {
        printf("Memory allocation failed!\n");
        return -1;
    }

    // Use the allocated memory
    for (int i = 0; i < 5; i++) {
        ptr[i] = i + 1;
        printf("%d ", ptr[i]);
    }

    free(ptr); // Free the allocated memory
    return 0;
}

Structs

Definition: A struct in C is a user-defined data type that groups variables of different data types under a single name.

Example:

#include <stdio.h>

struct Student {
    char name[50];
    int age;
    float gpa;
};

int main() {
    struct Student student1 = {"John Doe", 20, 3.5};

    printf("Name: %s\n", student1.name);
    printf("Age: %d\n", student1.age);
    printf("GPA: %.2f\n", student1.gpa);
    return 0;
}

Other Important Concepts

  • Enums: Enumeration types that help in defining named integer constants.
  • Unions: Like structs but share memory among variables, useful for memory optimization.
  • File Handling: Use functions like fopen, fclose, fwrite, and fread to work with files.