This document offers a comprehensive guide to arrays, vectors, and strings in C programming, covering their declaration, initialization, and manipulation. It explains how to work with one-dimensional and multidimensional arrays, implement vector-like functionality using dynamic memory allocation, a...
Arrays, Vectors and Strings in C
In C, arrays, vectors, and strings are used to store multiple values. Understanding
how to use them is crucial for managing large amounts of data and handling
dynamic memory.
1. Arrays in C
An array is a collection of variables of the same type that are stored in contiguous
memory locations. It allows you to store multiple values in a single variable.
1.1. Declaring and Initializing Arrays
To declare an array in C, specify the data type, the array name, and the size of the
array. For example:
#include <stdio.h>
int main() {
int numbers[5]; // Declaring an array of 5 integers
// Accessing array elements
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, numbers[i]);
}
return 0;
}
, 1.2. Array Initialization
You can initialize an array at the time of declaration:
#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30, 40, 50}; // Size is automatically determined
// Accessing array elements
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, numbers[i]);
}
return 0;
}
1.3. Multi-Dimensional Arrays
C supports multidimensional arrays, where each element is itself an array. A
common use case is a matrix.
#include <stdio.h>
int main() {
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}}; // 2x3 matrix
// Accessing elements of a 2D array
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("Element at [%d][%d]: %d\n", i, j, matrix[i][j]);
}
}
return 0;
}
The benefits of buying summaries with Stuvia:
Guaranteed quality through customer reviews
Stuvia customers have reviewed more than 700,000 summaries. This how you know that you are buying the best documents.
Quick and easy check-out
You can quickly pay through credit card or Stuvia-credit for the summaries. There is no membership needed.
Focus on what matters
Your fellow students write the study notes themselves, which is why the documents are always reliable and up-to-date. This ensures you quickly get to the core!
Frequently asked questions
What do I get when I buy this document?
You get a PDF, available immediately after your purchase. The purchased document is accessible anytime, anywhere and indefinitely through your profile.
Satisfaction guarantee: how does it work?
Our satisfaction guarantee ensures that you always find a study document that suits you well. You fill out a form, and our customer service team takes care of the rest.
Who am I buying these notes from?
Stuvia is a marketplace, so you are not buying this document from us, but from seller rileyclover179. Stuvia facilitates payment to the seller.
Will I be stuck with a subscription?
No, you only buy these notes for $8.39. You're not tied to anything after your purchase.