Menu
CoddyTech

A Small Vector Interface

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

C# List manages length and capacity inside an object. A C vector module must preserve these invariants explicitly and reset its state after destruction; two instances must not share accidental global state.

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

C# example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
class Program {

static void Main(){
var a=new List<int>();var b=new List<int>();a.Add(3);Console.WriteLine(a.Count+" "+b.Count);
}
}

C# 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 C# Developers

Practice on your own: Online C compiler