C Lesson 25 – Pointer Mini Project | Dataplexa

Pointer Mini Project – Student Marks Manager

You have now learned pointers, arrays, dynamic memory, and memory safety.

This mini project combines all of them into one meaningful program.

Do not worry about writing perfect code. Focus on understanding how pointers help manage memory dynamically.


Problem Statement

Create a program that:

  • Asks the user how many students are there
  • Dynamically allocates memory for marks
  • Stores marks using pointers
  • Displays all marks
  • Frees memory properly

The number of students is not known in advance.


Concepts Used

  • Dynamic memory allocation
  • Pointers and arrays
  • User input
  • Memory cleanup

Program Design (Think First)

Step-by-step plan:

  • Ask user for number of students
  • Allocate memory using malloc()
  • Store marks using pointer notation
  • Print all values
  • Free allocated memory

Complete Program


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

int main() {
    int n;
    int *marks;

    printf("Enter number of students: ");
    scanf("%d", &n);

    marks = (int*) malloc(n * sizeof(int));

    if (marks == NULL) {
        printf("Memory allocation failed");
        return 1;
    }

    for (int i = 0; i < n; i++) {
        printf("Enter marks of student %d: ", i + 1);
        scanf("%d", &marks[i]);
    }

    printf("\nStudent Marks:\n");
    for (int i = 0; i < n; i++) {
        printf("Student %d: %d\n", i + 1, *(marks + i));
    }

    free(marks);
    marks = NULL;

    return 0;
}

Code Explanation

Important points to notice:

  • malloc allocates memory based on user input
  • marks[i] and *(marks + i) are equivalent
  • Memory is freed at the end
  • Pointer is set to NULL for safety

Why This Project Matters

This program teaches you:

  • How real programs handle unknown data sizes
  • Why pointers are powerful
  • How memory must be managed manually

These skills are required in:

  • System programming
  • Embedded systems
  • Operating systems

Mini Enhancements (Optional)

  • Calculate average marks
  • Find highest and lowest marks
  • Resize memory using realloc

Quick Quiz

Q1. Why is malloc used in this program?

Because the number of students is not known at compile time.

Q2. What happens if malloc fails?

It returns NULL.

Q3. Is marks[i] same as pointer notation?

Yes.

Q4. Why do we free memory?

To prevent memory leaks.

Q5. Why set pointer to NULL after free?

To avoid accidental reuse.