Learn about how vectors work in C and C++, vector alternatives for C, and how to use dynamic memory allocation in C to get vector-like behavior.
![[Featured Image]: A person wearing a blue shirt and wearing headphones reviews code on a computer after exploring how vectors work in C.](https://d3njjcbhbojbot.cloudfront.net/api/utilities/v1/imageproxy/https://images.ctfassets.net/wp1lcwdav1p1/2VHHhDS0J2zKGKg9qO5Sm8/bef244f8c02cc5ffb5949e3346aeeeb5/GettyImages-1437209125-converted-from-jpg.webp?w=1500&h=680&q=60&fit=fill&f=faces&fm=jpg&fl=progressive&auto=format%2Ccompress&dpr=1&w=1000)
A vector is a sequence that stores elements of the same type and allows fast, constant-time access to any element.
Standard C does not include vectors, but you can replicate their behavior using dynamic memory allocation.
C's dynamic memory allocation allows data structures, such as arrays, to change size at runtime.
You can use vectors in C++ via the std::vector library defined in the <vector> header.
Learn more about how you can use memory allocation to create “vector-likes” in C. Afterward, you can start building your career in back-end development by enrolling in the IBM Back-End Development Professional Certificate. You’ll have the opportunity to master up-to-date practical skills and knowledge that back-end developers use in their daily roles and write back-end applications with object-oriented programming languages. By the end, you’ll have earned a Professional Certificate and facilitated the automation of the software development life cycle.
Vectors are a modern programming feature not included in standard C. Instead, they exist in C++, which extends the C programming language with object-oriented programming. However, you can use a different implementation, such as dynamic arrays, to achieve similar functionality to C++ vectors.
A vector is essentially a sequence of slots used to store values, with the size defined when the vector is created. Vectors always store the same type or class (like a string or int) within their slots, and allow you to access the 1,000th element as quickly as the second one. You can use vectors to store lists of items, like lines or shopping cart prices.
You can use vectors in C++ by accessing the std::vector library, which you define in the header <vector>. C++ vectors have a capacity, which refers to the amount of memory allocated to a given vector (accessed through the .capacity() function). This memory is automatically allocated to a vector as it expands or shrinks. C++ vectors also have a size, which is simply the number of elements within a given vector (accessed through the .size() function).
You can use vectors in C++ when you want an array that can dynamically handle its storage. This flexibility makes it especially useful when the number of elements is unknown. For instance, you could use a vector to collect user data when the number of items is unclear, since it automatically adjusts its size to accommodate everything. Additionally, vectors are very efficient at accessing their elements, making them an effective dynamic sequence container (compared to other containers like deques or lists).
You can create a “vector-like” structure in C by importing a user-created vector library. You can also manually implement custom vectors in C. To do this, you can create a struct that lays out memory in a way that mimics C++ vectors. You can then write your own expansion function that calls realloc() to double the capacity until the vector reaches the new size.
You will want to use a vector-like structure in C when you need an array that can dynamically allocate memory at runtime. This will allow you to adjust the size of the array at runtime, just like a C++ vector.
C's dynamic memory allocation allows data structures like arrays to change size at run time. You can do so through the use of the following functions:
C malloc(): Dynamically allocates a block of memory of a specified size and returns a pointer to it. It’s used when the required memory size is only known at runtime.
C calloc(): Dynamically allocates multiple contiguous memory blocks of a given type, similar to malloc(), but sets the default value to 0 and takes two parameters.
C free(): Releases memory allocated by malloc() or calloc() that the program does not automatically free, helping prevent wasted memory.
C realloc(): Changes the size of previously allocated memory, preserving existing values, while new space contains garbage values.
A typical array’s number of dimensions and size is set at compile time, while dynamically allocated arrays are allocated on the heap at run time. For instance, int a1[100] declares a static array named a1 containing 100 integers. Since this array is static, the number of integers it holds cannot change during runtime . Meanwhile, p_array = (int *)malloc(sizeof(int)*50) will declare a dynamically allocated array of 50 integers that can expand during run time using malloc().
Malloc, calloc, and realloc support vector behavior because they are dynamic memory allocation methods, which are a key component of vectors. You can use these methods to effectively create an array that functions similarly to a vector, even in C, where vectors are not natively present.
You can choose from a variety of C data structures as an alternative to vectors, depending on how dynamic you need your data structure to be. For instance, you can use a static array in C if your vector alternative does not need to change size during runtime. Other C dynamic data structures include linked lists and dynamically allocated arrays. Discover more about each alternative:
Read more: Types of Data Structures
Linked lists are a simple example of a dynamic data structure implemented using pointers. Linked lists also offer the following advantages over arrays: you can insert or remove items mid-list, and no initial size is necessary.
If you don't need your data structure to change in size at runtime, you can use a static array. Arrays store elements contiguously, allowing pointer arithmetic, and 2D arrays use row-major order. Additionally, statically declared arrays can be global or local.
If you want an array that can change during run time, you can use a dynamically allocated array. Heap memory (where the memory allocation takes place) assigns itself via pointers that store the address of the allocated space. You can then use malloc() with sizeof() to request a contiguous block of the required size.
Keep up with the latest industry insights, career guidance, and skill-building tips by joining our weekly Career Chat newsletter on LinkedIn. After that, explore our collection of free resources for back-end developers:
Watch on YouTube: Choosing Between Developer and Engineer Roles
Explore a career path: Web Development Career Paths: Explore Roles & Specializations
Learn about back-end frameworks: Which Back-End Framework Should I Learn?
With Coursera Plus, you can learn and earn credentials at your own pace from over 350 leading companies and universities. With a monthly or annual subscription, you’ll gain access to over 10,000 programs - just check the course page to confirm your selection is included.
Editorial Team
Coursera’s editorial team is comprised of highly experienced professional editors, writers, and fact...
This content has been made available for informational purposes only. Learners are advised to conduct additional research to ensure that courses and other credentials pursued meet their personal, professional, and financial goals.