Menu
CoddyTech

A Small Vector Interface

Lesson 35 of 48 in Coddy's C for Kotlin Developers course.

A Kotlin MutableList tracks its size and capacity internally, and each mutableListOf() call creates an independent instance whose capacity you never see. A C vector module must maintain those invariants explicitly and define initialization, growth failure and destruction behavior for independent instances.

A growable buffer needs data, length and capacity invariants. Destroying an owner should leave a documented empty state.

Kotlin example

fun main() {
    val a = mutableListOf<Int>()
    val b = mutableListOf<Int>()
    a.add(3)
    println("${a.size} ${b.size}")
}

Kotlin output:

1 0

C example

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>

int main(void) {
int a[1]={3};size_t an=1,bn=0;printf("%zu %zu\n",an,bn);(void)a;
return 0;
}

C output:

1 0
challenge icon

Challenge

Easy

Implement vec_init, vec_push and vec_destroy for IntVec. Preserve all pushed values in insertion order and keep independent vectors independent. Destroy frees owned data, then resets pointer/length/capacity; calling destroy twice is valid. Input is up to 64 integers. Driver prints count:sum and probes independence and cleanup.

Edit the unlocked source and header files. Keep the declared public API compatible with the visible locked main.c, which calls it directly. Do not add another main. All numeric task fixtures are small enough to avoid overflow unless the task explicitly checks a range. Print only the specified output; the driver supplies input parsing and output when shown.

Try it yourself

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){IntVec v,other;vec_init(&v);vec_init(&other);int values[64];size_t n=0;int value;while(n<64 && scanf("%d",&value)==1)values[n++]=value;for(size_t i=0;i<n;i++)if(!vec_push(&v,values[i])){vec_destroy(&v);return 2;}if(v.len!=n || other.len!=0)return 3;int sum=0;for(size_t i=0;i<v.len;i++){if(v.data[i]!=values[i])return 3;sum+=v.data[i];}printf("%zu:%d\n",v.len,sum);vec_destroy(&v);if(v.data || v.len || v.cap)return 3;vec_destroy(&v);vec_destroy(&other);return 0;}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in C for Kotlin Developers

Practice on your own: Online C compiler