C Programming

Practical C - Stack

Implement Stack in C

Guowei Lv

5 minute read

In this blog post, let’s implement a generic stack in C. We will do this by several iterations, from simple version to the full blown version step by step. An Integer Version Let’s start with implementing an integer stack. #include <assert.h> #include <stdio.h> #include <stdlib.h> typedef struct { // int array to store elements of the stack int *elems; // the actual length of the stack int logicalLen; // the allocated length of the array int allocLen; } stack; // Initialize a stack void StackNew(stack *s); // Dispose a stack void StackDispose(stack *s); // Push an element onto the stack void StackPush(stack *s, int value); // Pop an element from the stack int StackPop(stack *s); void StackNew(stack *s) { // allocate 4 elements for the array s->elems = (int *)malloc(4 * sizeof(int)); s->allocLen = 4; s->logicalLen = 0; } void StackDispose(stack *s) { free(s->elems); } void StackPush(stack *s, int value) { if (s->logicalLen == s->allocLen) { // double the size of the array if there is no free space in it s->elems = (int *)realloc(s->elems, 2 * s->allocLen * sizeof(int)); s->allocLen *= 2; } s->elems[s->logicalLen] = value; s->logicalLen++; } int StackPop(stack *s) { assert(s->logicalLen !

Practical C - Linear Search

Implement linear search in C

Guowei Lv

3 minute read

I start this blog series to show some of the trickier parts of C programming. In the first post, let’s implement the linear search in C. Integer Version Let’s imagine that we search on an integer array. Two things to notice here: The function needs the array size n as a separate parameter. Only the array’s address is passed in the function. Generic Basic Version Let’s write a more generic version that does not specify type.

Generic Programming in C

How to do generic programming in C

2 minute read

Generic programming is an important idea in programming. In languages like Java and C++, it can be done easily. In this post, I show how to do it in plain old C. We use the classic stack implementation. First, we implement an int version. This is stack.h: typedef struct { int *elems; int logLength; int allocLengh; } stack; void StackNew(stack *s); void StackDispose(stack *s); void StackPush(stack *s, int value); int StackPop(stack *s); This is stack.