A Small Vector Interface
Lesson 35 of 48 in Coddy's C for Rust Developers course.
Rust Vec owns initialized elements separately from capacity and releases them through Drop. C vector modules must explicitly maintain length/capacity and cleanup, and bytewise struct copies do not implement safe moves.
A growable buffer needs data, length and capacity invariants. Destroying an owner should leave a documented empty state.
Rust example
fn main(){
let a=vec![3];let b:Vec<i32>=Vec::new();println!("{} {}",a.len(),b.len());
}
Rust output:
1 0C 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 0Challenge
EasyImplement 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;}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in C for Rust Developers
1Compile and Compute
Run C Across FilesPrinting and CommentsTypes and InitializationInteger Division and RangeFloating ArithmeticRecap: Receipt Total4Functions and Interfaces
Function Arguments Are ValuesHeaders and LinkageMultiple Results via PointersConst Views and MutationRecap: Price Breakdown7Owned Dynamic Memory
Allocation and InitializationOwned Copies and freeGrowing Without Losing DataA Small Vector InterfaceRecap: Owned Integer Buffer2Decisions and Loops
Booleans and BranchesLogical OperatorsSwitch and Enumerated CasesLoop Bounds and ProgressRecap: Admission RulesPractice on your own: Online C compiler