Menu
CoddyTech

A Small Vector Interface

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

C++ vector maintains size, capacity, destruction and copy/move behavior. A C vector interface must provide these invariants explicitly. A bytewise C struct copy of an owning buffer can create two owners of one allocation.

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

C++ example

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <memory>
#include <algorithm>
#include <functional>
#include <variant>
#include <sstream>

int main(){
std::vector<int> a{3},b;std::cout<<a.size()<<" "<<b.size()<<"\n";
}

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