C Language Pointer Exercises: From scanf to swap, Mastering Pointers!

⭐C Language Pointer Exercises: From <span>scanf</span> to <span>swap</span>, Mastering Pointers!

Author: IoT Smart Academy

In the previous article, we started with this line:

scanf("%d", &a);

We clarified three things:

  1. <span>&a</span> is the “address” of a
  2. A pointer is a “variable specifically used to store addresses”
  3. <span>*p</span> is “finding the person inside the house by following the address”

Many students will say after reading: “I seem to understand a bit, but I still don’t know how to use it.”This article is meant to be hands-on: no new concepts, just four classic exercises to turn pointers from “heard of” into “I can write them”.

Table of Contents

  1. Using pointers to write a real <span>swap</span>
  2. Using pointers to manipulate arrays: One-click zeroing
  3. Using pointers to modify structures: Adding scores for students / Modifying sensor readings
  4. Small practical task: Using pointers to write a “batch score adding tool”

Each exercise includes: Problem → Illustrated thought process → Complete code → A memorable sentence.

1. Exercise 1: Using pointers to achieve a real <span>swap</span> (swapping two numbers)

📝 Requirement

Write a function <span>swap</span> that can swap the values of two variables in the <span>main</span> function:

int x = 3, y = 5;
swap(&x, &y);  // After calling, x=5, y=3

🚫 Incorrect implementation (many books mislead students from the start)

void swap(int a, int b) { // ❌
    int t = a;
    a = b;
    b = t;
}

This swaps the copies of a and b, and the outer x and y remain unchanged.

✅ Correct approach (following the pattern of scanf)

To modify a variable, you need to provide its address. Therefore:

  • <span>swap</span> needs to receive the addresses of x and y → parameters should be <span>int *a, int *b</span>
  • When calling, pass <span>&x, &y</span>
  • Inside the function, use <span>*a</span> and <span>*b</span> to modify the actual values

✅ Complete code

#include <stdio.h>

void swap(int *a, int *b) {
    int t = *a;   // t stores the value pointed to by *a (original x)
    *a = *b;      // Assign y's value to x
    *b = t;       // Assign original x to y
}

int main() {
    int x = 3, y = 5;

    printf("Before swap: x=%d, y=%d\n", x, y);
    swap(&x, &y);  // Pass addresses
    printf("After swap: x=%d, y=%d\n", x, y);

    return 0;
}

🧠 A memorable sentence

<span>scanf</span> modifies a by passing <span>&a</span>. How to modify x and y with <span>swap</span>? Pass <span>&x, &y</span>, and use <span>*</span> inside the function.

Pointers are not abstract; they are just applying the logic of <span>scanf</span> again.

2. Exercise 2: Using pointers to write an “array zeroing tool”

📝 Requirement

Write a function:

void setZero(int *a, int n);

That sets all elements of an integer array of length <span>n</span> to zero.

In the <span>main</span> function, use it like this:

int a[5] = {1, 2, 3, 4, 5};
setZero(a, 5);   // After calling, the array becomes 0 0 0 0 0

💡 Thought process

  • The array name <span>a</span> is already the address of the first element → passing it to the function is fine
  • The function parameter <span>int *a</span>: indicates “I received an address, and I will treat it as an array”
  • Using subscript or pointer arithmetic is fine; start with the version that is easier to understand

✅ Complete code (using subscript, easiest for students to accept)

#include <stdio.h>

void setZero(int *a, int n) {
    for (int i = 0; i < n; i++) {
        a[i] = 0;   // Equivalent to *(a + i) = 0;
    }
}

int main() {
    int a[5] = {1, 2, 3, 4, 5};

    printf("Before zeroing:");
    for (int i = 0; i < 5; i++) {
        printf("%d ", a[i]);
    }

    setZero(a, 5);  // Pass the address of the first element

    printf("\nAfter zeroing:");
    for (int i = 0; i < 5; i++) {
        printf("%d ", a[i]);
    }
    printf("\n");

    return 0;
}

🧠 A memorable sentence

The array name is the address; pass it to <span>int *a</span>, and use <span>a[i]</span> in the function.

You are already using “array pointer passing”; there’s no need to fear terms like “pointer array”.

3. Exercise 3: Using pointers to modify structures (Student & Sensor examples)

3.1 Student score adding tool <span>addScore</span>

📝 Requirement:

Write a function:

void addScore(Student *s, float delta);

Add <span>delta</span> points to the incoming student.

Define the structure (reuse your previous style)

typedef struct {
    int id;
    char name[20];
    float score;
} Student;

✅ Complete code

#include <stdio.h>

typedef struct {
    int id;
    char name[20];
    float score;
} Student;

void addScore(Student *s, float delta) {
    s->score += delta;  // Equivalent to (*s).score += delta;
}

int main() {
    Student stu = {1001, "Zhang", 85.0};

    printf("Before adding score: %s Score=%.1f\n", stu.name, stu.score);
    addScore(&stu, 5.0);  // Pass address
    printf("After adding score: %s Score=%.1f\n", stu.name, stu.score);

    return 0;
}

Key points explanation

  • <span>Student *s</span>: I received the address of a certain student
  • <span>s->score</span>: Accessing the structure member through the pointer, read as “the score of the student pointed to by s”
  • <span>-></span> is the shorthand syntax:<span>(*s).score</span>

3.2 Sensor reading update <span>updateSensor</span>

Switching to an IoT flavor:

typedef struct {
    int id;
    char loc[20];
    float value;
} Sensor;

void updateSensor(Sensor *s, float newValue) {
    s->value = newValue;
}

In the <span>main</span> function:

Sensor t = {101, "Room101", 26.5};
updateSensor(&t, 30.0);

The same logic applies, just switching from “student” to “device”, more aligned with your positioning.

🧠 A memorable sentence

To modify a structure in a function → pass the address, use <span>-></span>.<span>-></span> is the “pointer dot”.

4. Exercise 4: Small practical task — “Batch score adding tool” (connecting for student confidence)

📝 Requirement

There is an array of students <span>stu[3]</span>, write a function:

void bonusAll(Student *s, int n, float delta);

Add the same score to all students, for example, uniformly adding 2 points at the end of the semester.

✅ Complete code

#include <stdio.h>

typedef struct {
    int id;
    char name[20];
    float score;
} Student;

void bonusAll(Student *s, int n, float delta) {
    for (int i = 0; i < n; i++) {
        s[i].score += delta;  // s[i] is the i-th student
    }
}

int main() {
    Student stu[3] = {
        {1001, "Zhang", 80},
        {1002, "Li", 85},
        {1003, "Wang", 90}
    };

    printf("Before adding scores:\n");
    for (int i = 0; i < 3; i++) {
        printf("%d %s %.1f\n", stu[i].id, stu[i].name, stu[i].score);
    }

    bonusAll(stu, 3, 2.0);  // Pass the array name, equivalent to passing the address

    printf("\nAfter adding scores:\n");
    for (int i = 0; i < 3; i++) {
        printf("%d %s %.1f\n", stu[i].id, stu[i].name, stu[i].score);
    }

    return 0;
}

🧠 The pointer points here:

  • Parameter written as <span>Student *s</span>, argument passed as <span>stu</span> (array name)
  • In the function, use <span>s[i]</span> as an array
  • Essentially: The address of the first element is passed, but the syntax is almost identical to an array

5. Treat this article as a “pointer skill enhancement version” summary

  1. Don’t start memorizing from “a pointer is a variable of memory address”; think from <span>scanf("%d", &a)</span>.

  2. Whoever wants to modify you, just give them the address:<span>&variable_name</span>.

  3. On the function side, write pointers:<span>type *p</span>, use <span>*p</span> to modify.

  4. The array name is already an address, just pass it, and use <span>type *p</span> or <span>type p[]</span> for parameters.

  5. Accessing structure members with pointers is:<span>p->member_name</span>.

  6. Can write:

  • Pointer version of <span>swap</span>
  • Array zeroing function
  • Structure score adding / modifying readings 👉 already qualifies as “pointer entry level”.

Pointers are not meant to confuse; they are tools for solving problems. They allow others (functions) to truly modify your variables, which is their value.

Leave a Comment