In C, vectors are not a built-in data type like arrays or strings, but they can be
implemented using dynamic memory allocation, typically using pointers and the
malloc() function. A vector is essentially a dynamic array that can grow or shrink in
size as needed, providing more flexibility than static arrays.
Although C does not have a direct equivalent to vectors (like in C++), you can
simulate vectors using pointers and functions to manage dynamic memory.
1. Declaring and Initializing a Vector
To declare a vector in C, you first use a pointer and then allocate memory
dynamically using the malloc() function. This gives you the ability to change the
size of the vector during runtime.
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *vector;
int n;
printf("Enter the size of the vector: ");
scanf("%d", &n);
// Dynamically allocate memory for the vector
vector = (int *)malloc(n * sizeof(int));
if (vector == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Input vector elements
, for (int i = 0; i < n; i++) {
printf("Enter element %d: ", i + 1);
scanf("%d", &vector[i]);
}
// Output the vector elements
printf("Vector elements: ");
for (int i = 0; i < n; i++) {
printf("%d ", vector[i]);
}
printf("\n");
// Free the dynamically allocated memory
free(vector);
return 0;
}
In this example, vector is a pointer to an integer, and we use malloc() to allocate
space for n integers.
2. Dynamic Resizing of a Vector
One of the features of vectors is that they can grow or shrink in size during
runtime. In C, you can use the realloc() function to resize a dynamically allocated
array (vector).
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *vector;
int n;