9.10.25

Understanding Arrays in C



The Bookshelf Analogy & Book-Author Example

Arrays are one of the most essential concepts in C programming. They let you store multiple items of the same type in contiguous memory, making it easier to organize, access, and manipulate data. Think of an array as a bookshelf, where each shelf holds one book simple, organized, and neat!

In this blog, we’ll go through array concepts, C programs to create, display, and manage arrays, and a book-author example using arrays of strings.

The Bookshelf Analogy

Real-world item     Programming term Example
Bookshelf         Array     int favorite_numbers[8];
Book     Array element     favorite_numbers[0] = 100;
Shelf number     Index     favorite_numbers[3]
Number of shelves     Array size     8

Array Operations in C

creating, displaying, and managing arrays:

#include <stdio.h>

void DisplayIntArray(int given_array[], int array_data_size) {
    printf("Size of array is %d elements\n", array_data_size);
    printf("Array element values are:\n");
    for (int elementIndex = 0; elementIndex < array_data_size; elementIndex++) {
        printf("%d\n", given_array[elementIndex]);
    }
}

void DisplayFloatArray(float given_array[], int array_data_size) {
    printf("Size of array is %d elements\n", array_data_size);
    printf("Array element values are:\n");
    for (int elementIndex = 0; elementIndex < array_data_size; elementIndex++) {
        printf("%f\n", given_array[elementIndex]);
    }
}

int main() {
    // Integer Array Example
    int favorite_numbers[8];
    int favourite_numbers_length = sizeof(favorite_numbers) / sizeof(int);

    favorite_numbers[0] = 100;
    favorite_numbers[1] = 99;
    favorite_numbers[2] = 5;
    favorite_numbers[3] = 23;
    favorite_numbers[4] = 7;
    favorite_numbers[5] = 18;
    favorite_numbers[6] = 4;
    favorite_numbers[7] = 47;

    DisplayIntArray(favorite_numbers, favourite_numbers_length);

    // Another Integer Array Example
    int books[4] = {1984, 2001, 2010, 2020};
    DisplayIntArray(books, sizeof(books) / sizeof(int));

    // Float Array Example
    float favourite_fractions[3] = {3.14, 1.171, 2.72};
    DisplayFloatArray(favourite_fractions, sizeof(favourite_fractions) / sizeof(float));

    return 0;
}

Program Explanation

Creating Arrays
    int favorite_numbers[8];
    float favourite_fractions[3];

We declare arrays of a specific type and size.

Assigning Values

We can assign elements individually:
favorite_numbers[0] = 100;
favourite_fractions[1] = 1.171;

Or initialize at declaration:

int books[4] = {1984, 2001, 2010, 2020};

Displaying Arrays

We use functions with loops to display elements:
for (int i = 0; i < array_size; i++) {
    printf("%d\n", given_array[i]);
}

Array Size Calculation

int length = sizeof(favorite_numbers) / sizeof(int);

sizeof(favorite_numbers) → Total bytes of array
sizeof(int) → Size of one element
Divide to get number of elements

Important Points

Arrays store multiple values of the same type.
Indexing starts at 0.
Use loops to display or modify arrays efficiently.
Contiguous memory allows fast access.

Inserting & Deleting Elements

Since arrays have a fixed size, inserting or deleting requires shifting elements:

Delete the 2nd element example:

for(int i = 1; i < length - 1; i++) {
    favorite_numbers[i] = favorite_numbers[i + 1];
}
length--; // logically reduce array size

Book-Author Example Using Arrays of Strings

#include <stdio.h>

int main() {
    // Array of book titles
    char books[5][50] = {
        "Rich Dad Poor Dad",
        "1984",
        "The Book Theif",
        "The Alchemist",
        "Animal Farm"
    };

    // Array of authors corresponding to books
    char authors[5][50] = {
        "Robert Kiyosaki",
        "George Orwell",
        "Markus Zusak",
        "Paulo Coelho",
        "George Orwell"
    };

    printf("Book List:\n\n");

    // Display book and author
    for (int i = 0; i < 5; i++) {
        printf("Book: %s\nAuthor: %s\n\n", books[i], authors[i]);
    }

    return 0;
}

Explanation

books[5][50] → 5 book titles, each up to 50 characters.

authors[5][50] → 5 authors corresponding to books.

Using the same index, we link a book with its author.
Loop through arrays to display paired data.

Output


Book List:

Book: Rich Dad Poor Dad
Author: Robert Kiyosaki

Book: 1984
Author: George Orwell

Book: The Book Theif
Author: Markus Zusak

Book: The Alchemist
Author: Paulo Coelho

Book: Animal Farm
Author: George Orwell


8.10.25

Creating Array in C







Creating Arrays in C: Create, Insert, Delete & Display

Arrays are one of the most fundamental concepts in C programming. If you’ve ever tried to store multiple values like a list of favorite numbers  you’ve already needed arrays! Let’s explore how they work and what’s happening in this simple C program.

What is an Array?



An array is like a bookshelf it has a fixed number of slots (or compartments), and each slot can hold one book (a value).

In C, we can declare an array using:

data_type array_name[size];

Example:

int numbers[5];

This creates a space for 5 integers in memory all next to each other!

The Program

#include <stdio.h>

int main() {
  int favorite_numbers[5]; // Declaration of an array of 5 integers

  // Creating (assigning values)
  favorite_numbers[0] = 100;
  favorite_numbers[1] = 99;
  favorite_numbers[2] = 5;
  favorite_numbers[3] = 23;
  favorite_numbers[4] = 7;

  // Displaying values
  printf("My favorite numbers are %d\n%d\n%d\n%d\n%d\n", 
         favorite_numbers[0],
         favorite_numbers[1],
         favorite_numbers[2],
         favorite_numbers[3],
         favorite_numbers[4]);

  return 0;
}

Explanation:

1. Declaration

int favorite_numbers[5];

Here, we tell the compiler to reserve space for 5 integers in memory.
Each integer gets its own index — from 0 to 4.

Index Value
0
1
2
3
4

2. Creation (Assigning Values)

We now assign each books (array element) a value:

favorite_numbers[0] = 100;
favorite_numbers[1] = 99;
favorite_numbers[2] = 5;
favorite_numbers[3] = 23;
favorite_numbers[4] = 7;

Index Value
0 100
1 99
2 5
3 23
4 7

3. Display (Printing)

We can display the array elements one by one:


printf("My favorite numbers are %d\n%d\n%d\n%d\n%d\n",
       favorite_numbers[0],
       favorite_numbers[1],
       favorite_numbers[2],
       favorite_numbers[3],
       favorite_numbers[4]);

Output:

My favorite numbers are 100
99
5
23
7

You can use a Loop for Display

Instead of writing multiple printfs, we can use a loop:


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

This way, if you ever change the size of the array, the loop still works perfectly!

Deletion and Insertion? 

Arrays in C have a fixed size, meaning you can’t directly “delete” or “insert” new elements but you can shift values.

Example: Deleting 99
You can simply move all elements after 99 one step back:


for (int i = 1; i < 4; i++) {
    favorite_numbers[i] = favorite_numbers[i + 1];
}

Now 99 is gone, and the array looks like [100, 5, 23, 7, ?].

Summary

Operation Meaning Example
Create     Declare and assign values     int nums[5] = {1,2,3,4,5};
Insert     Place a value in an index     nums[2] = 10;
Delete     Shift elements to remove one     loop shifting technique
Display     Print array elements     for loop or printf


3.10.25

Exercise 28: Intermediate Makefiles in C


Hi! Today I’m gonna show you how to make a solid C project skeleton using Makefiles. Think of Makefiles like cooking recipes for your code—they list the ingredients (source files), the steps to prepare the dish (compiling and linking), and even how to clean up the kitchen (removing build junk). In this post, we’ll go step by step through Exercise 28: Intermediate Makefiles from Learn C the Hard Way. By the end, you’ll have a reusable skeleton that keeps your projects neat, organized, and super easy to build.

Project Skeleton Structure

what your project will look like?


c-skeleton/
├── LICENSE          # License for your project
├── README.md        # Project description (Markdown)
├── Makefile         # The magic recipe
├── bin/             # Where executables go
├── build/           # Where build artifacts go
├── src/             # Your source code (.c, .h)
│   └── dbg.h        # Debugging header (from Ex19)
└── tests/           # Automated tests

  • LICENSE → Defines usage rights.

  • README.md → Basic project instructions.

  • Makefile → The brain of the build system.

  • bin/ → Holds compiled programs.

  • build/ → Holds libraries/object files.

  • src/ → Your C source files.

  • tests/ → Automated test programs.

The Makefile Explanation 

a reference Makefile used in this project:

CFLAGS=-g -O2 -Wall -Wextra -Isrc -rdynamic -DNDEBUG $(OPTFLAGS)
LIBS=-ldl $(OPTLIBS)
PREFIX?=/usr/local

SOURCES=$(wildcard src/**/*.c src/*.c)
OBJECTS=$(patsubst %.c,%.o,$(SOURCES))

TEST_SRC=$(wildcard tests/*_tests.c)
TESTS=$(patsubst %.c,%,$(TEST_SRC))

TARGET=build/libYOUR_LIBRARY.a
SO_TARGET=$(patsubst %.a,%.so,$(TARGET))

all: $(TARGET) $(SO_TARGET) tests

dev: CFLAGS=-g -Wall -Isrc -Wall -Wextra $(OPTFLAGS)
dev: all

$(TARGET): CFLAGS += -fPIC
$(TARGET): build $(OBJECTS)
	ar rcs $@ $(OBJECTS)
	ranlib $@

$(SO_TARGET): $(TARGET) $(OBJECTS)
	$(CC) -shared -o $@ $(OBJECTS)

build:
	@mkdir -p build
	@mkdir -p bin

.PHONY: tests
tests: CFLAGS += $(TARGET)
tests: $(TESTS)
	sh ./tests/runtests.sh

clean:
	rm -rf build $(OBJECTS) $(TESTS)
	rm -f tests/tests.log
	find . -name "*.gc*" -exec rm {} \;
	rm -rf `find . -name "*.dSYM" -print`

install: all
	install -d $(DESTDIR)/$(PREFIX)/lib/
	install $(TARGET) $(DESTDIR)/$(PREFIX)/lib/

check:
	@echo Files with potentially dangerous functions.
	@egrep '[^_.>a-zA-Z0-9](str(n?cpy|n?cat|xfrm|n?dup|str|pbrk|tok|_)
	|stpn?cpy|a?sn?printf|byte_)' $(SOURCES) || true

Sections in the Makefile

1. Header Section

  • CFLAGS → Compiler options (debugging, warnings, optimizations).

  • LIBS → Linking libraries.

  • PREFIX → Default install path (/usr/local).

  • SOURCES & OBJECTS → Automatically detect .c files and create .o list.

2. Build Targets

  • all → Default target (builds everything).

  • dev → Developer build with extra warnings.

  • $(TARGET) → Builds static library .a.

  • $(SO_TARGET) → Builds shared library .so.

3. Directories

  • build: → Ensures build/ and bin/ exist.

4. Unit Tests

  • tests: → Compiles and runs unit tests.

  • Needs a helper script runtests.sh.

5. Cleaner

  • clean: → Removes build files, test logs, and compiler junk.

6. Install

  • install: → Copies library to system directory.

7. Checker

  • check: → Warns if dangerous C functions (strcpy, etc.) are used.

Unit Test Script

Create a file tests/runtests.sh:



#!/bin/sh

echo "Running unit tests:"

for i in tests/*_tests
do
    if test -f $i
    then
        if $VALGRIND ./$i 2>> tests/tests.log
        then
            echo $i PASS
        else
            echo "ERROR in test $i: see tests/tests.log"
            tail tests/tests.log
            exit 1
        fi
    fi
done

echo ""

This script runs all tests and reports if something fails.

Commands You Can Try

  • Clean build files:

make clean
  • Run security checks:

make check
  • Build everything:

make
  • Install library (needs root):

sudo make install

Extra Credit

  • Add a .c and .h file in src/ to test building.

  • Explore the regex in check: to learn about unsafe C functions.

  • Read more about automated unit testing in C.


rating System

Loading...

Understanding Arrays in C

The Bookshelf Analogy & Book-Author Example Arrays are one of the most essential concepts in C programming. They let you store multiple ...