Menu
CoddyTech

A Small Vector Interface

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

Python lists combine storage, length and growth. In C a vector struct can own a data pointer plus length and capacity, with functions maintaining invariants. This is a modular data structure, not a class. Destruction should reset state so repeated cleanup is harmless.

Python

a=[]
b=[]
a.append(3)
print(len(a),len(b))

C17

#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;
}

Porting rule

Keep vector length, capacity and ownership consistent after each operation.

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 Python Developers

Practice on your own: Online C compiler