In this c programming tutorial we are going to see code for implementing vector in c language or creating array of size N (Any size array) in language. So let’s proceed, in this c programming tutorial we’re just going to create a dynamically sized array of integers. Here’s what the definition of a vector interface might look like:

Note that we are writing this code in header file and we will be calling it vector.h

Implementing Vector

Below is the code for implementation of the interface we defined (vector.h) above. We will be naming this code as vector.c

What we did here is simply allocated memory using malloc() function. The size of the memory allocated will be the simply the size of the vector we want, multiplied by the size of type of the vector we are going to create. Here we are creating Vector for storing integer values, so the size of memory would be “sizeof(int) * vector->capacity”. Note that if you want create vector for storing values with some other data type, then simply change the data type of the “* data” in structure we have defined to required one and that’s it.


Using our Vector

In this usage example, we keep things simple and just pass around the pointer to a variable called vector allocated on the stack, we will be naming this file as vector-usage.c


Leave a comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: