Resources for C

by Fredrik Daneby

Useful links

C reference[ https://en.cppreference.com/w/c.html ]
The GNU compiler collection[ https://gcc.gnu.org/ ]
The GNU debugger[ https://sourceware.org/gdb/ ]
Compiler explorer[ https://godbolt.org/ ]

Snippets

Bash script for building

#!/bin/bash
################################################################################
# Date: 2025-06-08
# Author: Fredrik Daneby
#
# A small script to build and run simple C programs
#
# Usage:
#            $bash build.sh [filename]
################################################################################

# First parameter must not be zero length
if [ -n "$1" ]
 then

    # Strip file extension
    base=$(basename "$1" .c)

    ### Build

    cmdline="gcc $base.c -o $base"
    echo "Build: [ $cmdline ]"
    $cmdline

    ### Run
    echo "Run: [ $base ]"
    ./$base

else
    echo "Sorry. Can not continue without a filename."
fi 

Hello world

#include <stdio.h>

int main(void) {

    printf("Hello world\n");
    
    return 0;
    
}

Types

Platform dependent types

/* 
Prints sizes and limits of C types are defined in limits.h. Note that
integer types should be implemented using fixed width types defined in 
inttypes.h to ensure consistency across different platforms.
*/

#include <stdbool.h>
#include <stdio.h>
#include <limits.h>
#include <float.h>

int main(void) {

    printf("Sizes and limits of C types as defined in limits.h\n\n");

                                bool    a_min = 0;
                                bool    a_max = 1;
    
    unsigned                    char    b_min = 0;
    unsigned                    char    b_max = UCHAR_MAX;
    signed                      char    c_min = SCHAR_MIN;
    signed                      char    c_max = SCHAR_MAX;

    unsigned                    short   d_min = 0;
    unsigned                    short   d_max = USHRT_MAX;
    signed                      short   e_min = SHRT_MIN;
    signed                      short   e_max = SHRT_MAX;

    unsigned                    int     f_min = 0;
    unsigned                    int     f_max = UINT_MAX;
    signed                      int     g_min = INT_MIN;
    signed                      int     g_max = INT_MAX;

    unsigned    long            int     h_min = 0;
    unsigned    long            int     h_max = ULONG_MAX;
    signed      long            int     i_min = LONG_MIN;
    signed      long            int     i_max = LONG_MAX;

    unsigned    long    long    int     j_min = 0;
    unsigned    long    long    int     j_max = ULLONG_MAX;
    signed      long    long    int     k_min = LLONG_MIN;
    signed      long    long    int     k_max = LLONG_MAX;

    /* Floating point types limits are defined in float.h on Linux */
    float l_min = FLT_MIN;
    float l_max = FLT_MAX;

    double m_min = DBL_MIN;
    double m_max = DBL_MAX;

    long double n_min = LDBL_MIN;
    long double n_max = LDBL_MAX;

    printf("\n- pointer -\n");
    printf("Size of pointer: %zu bytes\n", sizeof(int*));

    printf("\n- bool -\n");
    printf("Size of bool: %zu bytes\n", sizeof(a_min));
    printf("\t\tbool\tmin: %d\t\tmax: %d\n", a_min, a_max);
        
    printf("\n- char -\n");
    printf("Size of char: %zu bytes\n", sizeof(b_min));
    printf("unsigned\tchar\tmin: %u\t\tmax: %u\n", b_min, b_max);
    printf("signed\t\tchar\tmin: %d\tmax: %d\n", c_min, c_max);
    
    printf("\n- short -\n");
    printf("\nSize of short: %zu bytes\n", sizeof(d_min));
    printf("unsigned\tshort\tmin: %hu\t\tmax: %hu\n", d_min, d_max);
    printf("signed\t\tshort\tmin: %hd\tmax: %hd\n", e_min, e_max);

    printf("\n- int -\n");
    printf("\nSize of int: %zu bytes\n", sizeof(f_min));
    printf("unsigned\tint\tmin: %u\t\tmax: %u\n", f_min, f_max);
    printf("signed\t\tint\tmin: %u\tmax: %d\n", g_min, g_max);

    printf("\n- long int -\n");
    printf("\nSize of long int: %zu bytes\n", sizeof(h_min));
    printf("unsigned long\tint\tmin: %lu\t\t\t\tmax: %lu\n", h_min, h_max);
    printf("signed long\tint\tmin: %ld\tmax: %ld\n", i_min, i_max);

    printf("\n- long long int -\n");
    printf("\nSize of long long int: %zu bytes\n", sizeof(j_min));
    printf("unsigned long long\tint\tmin: %u\t\t\t\tmax: %lu\n", j_min, j_max);
    printf("signed long long\tint\tmin: %lld\tmax: %lld\n", k_min, k_max);

    printf("\n - float -\n");
    printf("\nSize of float: %zu bytes\n", sizeof(l_min));
    printf("float\tmin: %f\tmax: %f\n", l_min, l_max);
    printf("float\tmin: %e\tmax: %e\n", l_min, l_max);

    printf("\n - double -\n");
    printf("\nSize of double: %zu bytes\n", sizeof(m_min));
    printf("float\tmin: %lf\tmax: %lf\n", m_min, m_max);
    printf("float\tmin: %le\tmax: %le\n", m_min, m_max);

    printf("\n - long double -\n");
    printf("\nSize of long double: %zu bytes\n", sizeof(n_min));
    printf("float\tmin: %Lf\tmax: %Lf\n", n_min, n_max);
    printf("float\tmin: %Le\tmax: %Le\n", n_min, n_max);

}

Fixed width integer types

/*
Prints sizes and limits of fixed witdh integer types as defined in inttypes.h
*/

#include <inttypes.h>
#include <stdio.h>

int main(void) {

    printf("Sizes and limits of integer types as defined in inttypes.h\n\n");

    printf("Size of int8_t:\t\t%zu\tmin:%d\t\t\tmax:%d\n", sizeof(int8_t), INT8_MIN, INT8_MAX);
    printf("Size of int16_t:\t%zu\tmin:%d\t\t\tmax:%d\n", sizeof(int16_t), INT16_MIN, INT16_MAX);
    printf("Size of int32_t:\t%zu\tmin:%d\t\t\tmax:%d\n", sizeof(int32_t), INT32_MIN, INT32_MAX);
    printf("Size of int64_t:\t%zu\tmin:%ld\tmax:%ld\n", sizeof(int64_t), INT64_MIN, INT64_MAX);
    printf("\n");
    printf("Size of uint8_t:\t%zu\tmin:%u\t\t\t\tmax:%u\n", sizeof(uint8_t), 0, UINT8_MAX);
    printf("Size of uint16_t:\t%zu\tmin:%u\t\t\t\tmax:%u\n", sizeof(uint16_t), 0, UINT16_MAX);
    printf("Size of uint32_t:\t%zu\tmin:%u\t\t\t\tmax:%u\n", sizeof(uint32_t), 0, UINT32_MAX);
    printf("Size of uint64_t:\t%zu\tmin:%u\t\t\t\tmax:%lu\n", sizeof(uint64_t), 0, UINT64_MAX);
    return 0;
}

Structs and unions (sizes)

#include <inttypes.h>
#include <stdio.h>

typedef struct {
    uint8_t prefix;         // 1 byte
    uint32_t multiplier;    // 4 bytes
} metric_prefix;

typedef struct {
    uint32_t x;             // 4 bytes
    uint32_t y;             // 4 bytes
} point_2D ;

typedef struct {
    uint32_t x;             // 4 bytes                 
    uint32_t y;             // 4 bytes
    uint32_t z;             // 4 bytes
} point_3D;

union number {
    uint32_t smaller;       // 4 bytes
    uint64_t larger;        // 8 bytes
};

union point {
    point_2D one_point;
    point_3D another_point;
};

int main(void) {
    
    union number n;
    union point p;

    printf("Size of metric prefix struct: %zu\n", sizeof(metric_prefix));
    printf("Size of 2D point struct: %zu\n", sizeof(point_2D));
    printf("Size of 3D point struct: %zu\n", sizeof(point_3D));
    printf("Size of number union: %zu\n", sizeof(n));
    printf("Size of point union: %zu\n", sizeof(p));
        
    return 0;

}

Arrays

Declaration and initialization

/*
A simple example of how to declare and initialize arrays in C
*/

#include <stdio.h>
#include <inttypes.h>

int main(void) {

    uint32_t numbers[4] = {1, 2, 3, 4};
    printf("Numbers: ");
    for (int i = 0; i < 4; i++) { printf("%u ", numbers[i]); }

    uint8_t letters[]   = {'a', 'b', 'c', 'd'};
    printf("\nLetters: ");
    for (int i = 0; i  <4; i++) { printf("%c(%u) ", letters[i], letters[i]); }
    
    printf("Size of numbers: %zu\nSize of letters: %zu\n", sizeof(numbers), sizeof(letters));

    return 0;
}

Simple pointer arithmetics

/*
A simple example of how pointer arithmetics can be used on arrays.
*/
#include <inttypes.h>
#include <stdio.h>

int main(void) {

    #define ALPHABET_SIZE 26                    

    // Iterate array using []
    uint8_t letters[ALPHABET_SIZE] = {0};
    for (uint8_t i = 0; i < ALPHABET_SIZE; i++) { letters[i] = 65 + i; }
    for (uint8_t i = 0; i < ALPHABET_SIZE; i++) { printf("%c ", letters[i]); }
    printf("\n");
    printf("The size of the array letters is %zu bytes\n\n", sizeof(letters));

    // Iterate array using pointer arithmetics
    uint8_t* alphabet = letters;
    for (int i = 0; i < ALPHABET_SIZE; i++) {
        printf("%c ", *(alphabet+i));
    }
    printf("\n");
    printf("The size of the pointer alphabet is %zu\n", sizeof(alphabet));
    printf("The array size can not be deduced from this pointer\n");
    
    return 0;

}

Dynamic allocation

/*
An example of a dynamically allocated array
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>

// In the real world, this number would not be known at compile time
#define BUFFER_SIZE 10                

int main(void) {

    // Allocate memory for buffer array
    uint8_t* buffer = malloc( BUFFER_SIZE * sizeof(uint8_t) );

    // Make sure we did not get a NULL pointer back
    if (NULL == buffer) {
        fprintf( stderr, "Sorry, unable to allocate %zu bytes for buffer\n", BUFFER_SIZE*sizeof(uint8_t));
        exit( EXIT_FAILURE );
    }
    else {
        printf("%zu bytes were successfully allocated\n", BUFFER_SIZE*sizeof(uint8_t));

        // Set each element value to element index
        for(uint8_t i = 0; i < BUFFER_SIZE; i++) {
            buffer[i] = i;
        }
    }

    // Print array
    for (uint8_t i = 0; i < BUFFER_SIZE; i++) {
        printf("buffer[%u] = %u\n", i, buffer[i]);
    }
    
    // Release the memory
    free(buffer);
    
    return EXIT_SUCCESS;

}

Strings

Initialization

/*
An example of C strings. Note that C strings MUST end with a '\0'.
This is added implicitly by initializations with strings (below), but must be
added manually sometimes.
*/
#include <stdlib.h>
#include <stdio.h>

int main(void) {

    /* String constant known at compile time */
    const char* animal = "Mongoose";
    printf("Animal is: %s\n", animal);

    /* A string can be accessed like an array */
    char letters[] = "A-B-C-D-E-F-G";
    char* ptr_letters = letters;

    // Strings should be NULL terminated. This would turn into an infinite loop
    // reading into unknown memory otherwise.
    while (*ptr_letters != '\0') {       
        printf("%c ", *ptr_letters);
        ptr_letters++;
    }
    printf("\n");

    return EXIT_SUCCESS;
    
}

Compare, search and join

/*
Examples of string compare, find substring and joining strings. Note that C 
strings MUST end with a '\0'. This is added implicitly by initializations with 
strings (below), but must be added manually sometimes.
*/

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

int main(void) {

    char letters[] = "A-B-C-D-E-F-G";
    char numbers[] = "1-2-3-4-5-6-7";

    // Get string length
    printf("String letters is %lu characters long\n", strlen(letters));
    printf("String numbers is %lu characters long\n", strlen(numbers));

    // Compare strings
    char match[] = "A-B-C-D-E-F-G";
    if (strcmp(letters, match) == 0) {
        printf("letters equals %s\n", match);
    }
    else {
        printf("letters is not equal to %s\n", match);
    }

    // Find first occurence of pattern in string
    char pattern[] = "D-E";
    char* ptr_result = strstr(letters, pattern);

    if (NULL != ptr_result) {
        printf("Found string %s at %s in letters\n", pattern, ptr_result);
    }

    // Concatenate strings
    strcat(letters, numbers);                   
    printf("letters is now: %s\n", letters);

    return EXIT_SUCCESS;
    
}

Find occurences of token

/*
An example of how strchr() can be used to find all occurences of a token in 
a string. Note that C strings MUST end with a '\0'.
This is added implicitly by initializations with strings (below), but must be
added manually sometimes.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(void) {

    char letters[] = "A-B-C-D-E-F-G";       // String to search
    
    char* ptr_result;                       // Pointer to match (or NULL)
    char token = '-';                       // Token to search for

    ptr_result = strchr(letters, token);

    while (NULL != ptr_result) {            // Iterate until search fails
        printf("Token %c was found at index %ld\n", token, ptr_result - letters);
        ptr_result = strchr(ptr_result + 1, token); // Step forward and search
    }

    return EXIT_SUCCESS;
    
}

Functions

Command line arguments

/* =============================================================================
Invoke at command-line with varying arguments such as:

./arguments 1 2 3 4
./arguments katt hund fisk

==============================================================================*/

#include <stdio.h>

int main(int argc, char* argv[]) {

    printf("I was called with %d arguments\n", argc);

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

    return 0;

}

Simple function declaration, definition and call

/*
An example of a function declaration and definition in C
*/
#include <stdio.h>
#include <inttypes.h>

// Declaration (Redundant in this program. Usually in .h file)
int32_t add(int32_t operand_1, int32_t operand_2);

// Definition
int32_t add(int32_t operand_1, int32_t operand_2) {
    return operand_1 + operand_2;
}

int main(void) {

    int32_t number_1 = 10;
    int32_t number_2 = 20;
    int32_t result = add(number_1, number_2);            // Function call
    printf("Addition result: %d\n", result);

    return EXIT_SUCCESS;
}

Pointers

/* An example of pointers */

#include <stdio.h>

int main(void) {

    int number = 10;
    int* ptr_number = &number;

    printf("number is %d and ptr_number is %p but pointing to the value %d.\n", 
        number, ptr_number, *ptr_number);
    printf("Size of ptr_number is %zu.\n", sizeof(ptr_number));

    /* 
    IRL, it would be silly to use a pointer to an integer.

    Pointers are useful for data structures that are expensive to copy or 
    dynamically allocated (which should be avoided).
    */

    char* message = "Guten Tag!";   // message is a pointer to a char

    /* message is passed as a pointer to the library function printf() */
    printf("message is a pointer(%p) and pointing to a byte %u which can be \
intepreted as an ASCII character %c.\n", 
        message, *message, *message);              // * is used to acess value

    printf("message is null terminated during initialization and can be written\
 as a string: %s\n", message);
    
       
    return 0;

}

Pointers, types and casting

/* Pointers and casting */

#include <stdio.h>
#include <inttypes.h>

int main(void) {

    /* When copying pointers, the types of the pointers must be compatible */
    char*       message         = "God morgon";
    uint8_t*    utf8_message    = message;          // Probably OK
    uint16_t*   utf16_message   = message;          // Ok but weird

    /* Compiler will warn but not croak */

    printf("Size of character in message: %zu bytes\n", 
        sizeof(*message));                                          // 1 byte
    printf("Size of character in utf8_message: %zu bytes\n", 
        sizeof(*utf8_message));                                     // 1 byte
    printf("Size of character in utf16_message: %zu bytes\n", 
        sizeof(*utf16_message));                                    // 2 bytes

    /* What happens to the characters? */


    /* Casting from 16-bit values to 8-bit values causes loss of data */
    uint16_t utf16_buffer[10] = {256};
    printf("The first value of utf16_buffer is %u\n", utf16_buffer[0]);

    /* The next line will (should) cause a compiler warning */
    char* backup = utf16_buffer;          
    printf("The first value of backup is %u\n", backup[0]);

    /* The next line will NOT cause a compiler warning. Explicit cast. */
    char* backup2 = (char*) utf16_buffer; 
    printf("The first value of backup2 is %u\n", backup2[0]);

    return 0;}

Passing data structures as pointers to functions

/*
An example of how a data structure can be passed as a pointer to avoid expensive
copying. How is this done in Python?
*/

#include <inttypes.h>
#include <stdio.h>

#define BUFFER_LENGTH_NAME  255

typedef struct {
    uint8_t name[BUFFER_LENGTH_NAME];
    uint8_t age;
} person;

void print_name( person* p ) {
    printf("Name of person is: %s\n", p->name);
}

int main(void) {

    person bosse = {"Bosse", 15};

    print_name(&bosse);
    
    return 0;
}

Program flow

Basic loops

/* Basic loops */

#include <stdio.h>

int main(void) {

    printf("For-loop:\n");
    for (int i = 0; i < 10; i++ ){
        printf("%d ", i);
    }
    
    printf("\nWhile-loop: \n");

    int j = 10;
    while(j >= 0) {
        printf("%d ", j);
        j--;
    }

    return 0;
}

Basic switch and if-else

/* Basic switch and if-else */

#include <stdio.h>

int main(void) {

    int value = 0;

    printf("The value is ");
    switch (value) {
        case 0:
            printf("0");
            break;
        case 1:
            printf("1");
            break;
        case 2:
            printf("2");
            break;
        default:
            printf("ERROR");
    }

    printf("\nI´m pretty sure the value is ");
    
    if (value == 0) {
        printf("0");
    }
    else if (value == 1) {
        printf("1");
    }
    else {
        printf("2");
    }
    printf("\n");
    return 0;
} 

File I/O

Write to file

/*
A simple program to write to a file. Output file will be placed
in current working directory.
*/

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <inttypes.h>

/* fprintf is used to write a string to a file */
int writer( const char* filename, const char* msg ) {

    FILE* filehandle = fopen(filename, "w");	// w for write

    if( NULL == filehandle ) {
        fprintf( stderr, "Sorry. Could not open file %s. %s\n", filename, strerror( errno ) );
        exit( EXIT_FAILURE );
    }
    if (NULL == msg) {
        fprintf( stderr, "Sorry. Message to write was NULL.\n");
        exit( EXIT_FAILURE );
    }

    int bytes_written = fprintf(filehandle, "%s\n", msg);

    fclose(filehandle);

    return bytes_written;

}

int main(void) {

    const char* filename    = "c_output_test.txt";
    const char* msg         = "A B C D E F G H I";
    
    int bytes_written = writer(filename, msg);
    printf("%d bytes were written to %s\n", bytes_written, filename);

    return 0;
}

Read file

/*
The same program as above but with an additional function reader, which read the
output text
*/

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <inttypes.h>

#define READ_BUFFER_BYTES   1024

/* fprintf is used to write a string to a file */
int writer( const char* filename, const char* msg ) {

    FILE* filehandle = fopen(filename, "w");

    if( NULL == filehandle ) {
        fprintf( stderr, "Sorry. Could not open file %s. %s\n", filename, strerror( errno ) );
        exit( EXIT_FAILURE );
    }
    if (NULL == msg) {
        fprintf( stderr, "Sorry. Message to write was NULL.\n");
        exit( EXIT_FAILURE );
    }

    int bytes_written = fprintf(filehandle, "%s", msg);

    if( fclose( filehandle ) != 0 ) {
        fprintf( stderr, "Sorry. Could not close file. %s\n", strerror( errno ) );
        exit( EXIT_FAILURE );
    }

    return bytes_written;

}

int reader(const char* filename, uint8_t* buffer, uint32_t buffer_size) {

    FILE* filehandle = NULL;

    // Open a filehandle
    filehandle = fopen(filename, "r");      // r for read
    
    if( NULL == filehandle ) {
        fprintf( stderr, "Sorry. Could not open file %s. %s\n", filename, strerror( errno ) );
        exit( EXIT_FAILURE );
    }

    // Attempt to read buffer_size bytes from filehandle    
    int bytes_read = fread(buffer, sizeof(uint8_t), buffer_size, filehandle);

    printf("%d bytes read\n", bytes_read);      // Show number of bytes read
    buffer[bytes_read] = '\0';                  // Terminate buffer string
    printf("Read:[%s]\n", buffer);              // Show what we read
    
    // Close the filehandle
    if( fclose( filehandle ) != 0 ) {
        fprintf( stderr, "Sorry. Could not close file. %s\n", strerror( errno ) );
        exit( EXIT_FAILURE );
    }

    return bytes_read;

}

int main(void) {

    const char* filename    = "c_output_test.txt";
    const char* msg         = "A B C D E F G H I J K L M";
    
    int bytes_written = writer(filename, msg);
    printf("%d bytes were written to %s\n", bytes_written, filename);

    uint8_t read_buffer[READ_BUFFER_BYTES] = {0};

    reader(filename, read_buffer, READ_BUFFER_BYTES);

    return 0;
}

Threads

pthreads

#include <stdio.h>
#include <inttypes.h>
#include <time.h>
#include <pthread.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

/* 
To get information about processors on Linux. 
 On Windows, check out GetSystemInfo()
 */
#include <sys/sysinfo.h>

typedef struct {
    
    uint8_t id;
    float number;
    float result;

} thread_info;


// The function that each thread runs when started. 
// The structure info contains thread id and a number to do work on. 
// Result is stored in the struct

static void* thread_work(thread_info* info) {
    
    uint32_t iterations = 50000 * (rand() % (1000 + 1));

    printf("[thread %d] Going to work with number %f for %d iterations\n", 
        info->id, info->number, iterations);

    // Do some dummy work
    for (int i = 0; i < iterations; i++) {
        info->result = info->number * (rand() % (1000 + 1));
        info->result = info->result / (rand() % (1000 + 1));
    
    }
    
}

int main(void) {

    printf("This system has %d processors configured and "
        "%d processors available.\n",
        get_nprocs_conf(), get_nprocs());

    uint8_t threadcount = 4;          // Set number of threads to run

    // Allocate memory for pointers to thread and argument structures
    pthread_t** threads     = malloc(threadcount * sizeof(pthread_t*));
    thread_info** arguments = malloc(threadcount * sizeof(thread_info*));

    if ((NULL == threads) || (NULL == arguments)) {
        fprintf(stderr, "Sorry. Unable to allocate memory for thread and \
argument pointers\n");
        exit(EXIT_FAILURE);
    }

    srand(time(NULL));                      // Seed random numbers

    // Allocate memory for thread and argument structures. Set random number
    // for each argument struct
    for (int i = 0; i < threadcount; i++) {
        threads[i] = (pthread_t*)malloc(sizeof(pthread_t));
        arguments[i] = (thread_info*)malloc(sizeof(thread_info));
        if ((NULL == threads[i]) || (NULL == arguments[i])) {
            fprintf(stderr, "Sorry. Unable to allocate memory for thread and \
argument structures\n");
            exit(EXIT_FAILURE);
        }
    
        arguments[i]->id = i;
        arguments[i]->number = rand() % (1000 + 1);
    }

    // Create threads
    for (int i = 0; i < threadcount; i++) {
        int result = pthread_create(threads[i], NULL, thread_work, arguments[i]);
        if (0 != result) {
            fprintf(stderr, "Sorry. Unable to create thread %d: %s\n", i, strerror(errno));
            exit(EXIT_FAILURE);
        }

        pthread_join(*threads[i], NULL);    // Wait for thread to complete

        printf("Thread %d started...\n", arguments[i]->id);

    }

    // Free memory for thread and argument structures
    for (int i = 0; i < threadcount; i++) {
        free(threads[i]);
        free(arguments[i]);
    }

    // Free memory for pointers threads and argument structures
    free(threads);
    free(arguments);

    return 0;
}