Define a matrix in C
Categories:
Defining and Manipulating Matrices in C
Learn the fundamental ways to define, initialize, and perform basic operations on matrices using C programming language, covering both static and dynamic allocation.
Matrices are fundamental data structures used in various scientific and engineering applications, including linear algebra, computer graphics, and image processing. In C, you can represent a matrix using multi-dimensional arrays. This article will guide you through defining and manipulating matrices, exploring both static and dynamic memory allocation approaches.
Static Matrix Definition
The simplest way to define a matrix in C is by using a two-dimensional array. This approach is suitable when the size of the matrix is known at compile time. However, it requires fixed dimensions, which might not be flexible for all applications. Remember that C stores multi-dimensional arrays in row-major order.
#include <stdio.h>
int main() {
// Define a 3x3 matrix
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing elements
printf("Element at (0, 0): %d\n", matrix[0][0]); // Output: 1
printf("Element at (1, 2): %d\n", matrix[1][2]); // Output: 6
// Printing the entire matrix
printf("\nMatrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
Example of a statically defined 3x3 matrix in C.
Dynamic Matrix Definition using Pointers to Pointers
For matrices whose size is not known until runtime, dynamic memory allocation is essential. In C, this is commonly achieved using pointers to pointers (e.g., int**
). This allows you to allocate memory for rows and then for columns within each row, creating a jagged array structure which can represent a matrix. This method provides maximum flexibility as both the number of rows and columns can be specified during execution.
#include <stdio.h>
#include <stdlib.h>
int main() {
int rows = 3;
int cols = 4;
// Allocate memory for 'rows' number of row pointers
int** matrix = (int**)malloc(rows * sizeof(int*));
if (matrix == NULL) {
fprintf(stderr, "Memory allocation failed for rows!\n");
return 1;
}
// Allocate memory for 'cols' number of integers for each row
for (int i = 0; i < rows; i++) {
matrix[i] = (int*)malloc(cols * sizeof(int));
if (matrix[i] == NULL) {
fprintf(stderr, "Memory allocation failed for columns in row %d!\n", i);
// Free previously allocated rows before exiting
for (int k = 0; k < i; k++) {
free(matrix[k]);
}
free(matrix);
return 1;
}
}
// Initialize and print the matrix
printf("\nDynamically allocated Matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = i * cols + j + 1;
printf("%d ", matrix[i][j]);
}
printf("\n");
}
// Free the dynamically allocated memory
for (int i = 0; i < rows; i++) {
free(matrix[i]);
}
free(matrix);
return 0;
}
Dynamic matrix allocation using pointers to pointers (int**
).
Dynamic Matrix Definition using a Single Pointer (Contiguous Memory)
An alternative approach for dynamic matrix allocation is to use a single pointer (int*
) and treat the 2D matrix as a 1D array in contiguous memory. This can sometimes offer better cache performance due to memory locality. To access an element matrix[i][j]
, you would use the formula *(matrix + i * cols + j)
or matrix[i * cols + j]
.
#include <stdio.h>
#include <stdlib.h>
int main() {
int rows = 3;
int cols = 4;
// Allocate memory for 'rows * cols' integers in a single block
int* matrix = (int*)malloc(rows * cols * sizeof(int));
if (matrix == NULL) {
fprintf(stderr, "Memory allocation failed!\n");
return 1;
}
// Initialize and print the matrix
printf("\nDynamically allocated Contiguous Matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i * cols + j] = i * cols + j + 10;
printf("%d ", matrix[i * cols + j]);
}
printf("\n");
}
// Free the dynamically allocated memory
free(matrix);
return 0;
}
Dynamic matrix allocation using a single pointer for contiguous memory.
Comparison of different matrix memory layouts in C.