Hello folks, today we are gonna see how pointer arithmetic actually is and how we can use pointers in our simple program. I’ve implemented a simple array print function that populates a double dimensional array and prints it according to its value.
#include <stdio.h>
#include <stdlib.h>
#define ROW 3
#define COLUMN 4
void print_matrix(int array[][COLUMN], int row, int column) {
for(int i = 0 ; i < row ; i++) {
for (int j = 0 ; j < column ; j++) {
printf("%d ",array[i][j]);
}
printf("\n");
}
}
void print_matrix2(int **matrix, int row, int column) {
for(int i = 0 ; i < row ; i++) {
for (int j = 0 ; j < column ; j++) {
printf("%d ",*((*(matrix+i))+j));
}
printf("\n");
}
}
void populate_matrix1(int matrix[][COLUMN], int row , int column) {
for(int i = 0 ; i < row; i ++){
for(int j = 0 ; j < column ; j++) {
matrix[i][j] = i*j + j + 1;
}
}
}
void populate_matrix2(int **matrix, int row , int column) {
for(int i = 0 ; i < row; i ++){
for(int j = 0 ; j < column ; j++) {
(*(*(matrix+i)+j)) = i*j + j + 1;
}
}
}
int main() {
printf("Hello World\n");
int array[ROW][COLUMN];
int **matrix;
matrix = (int**)malloc(sizeof(int*)*ROW);
for(int i = 0 ; i < ROW ; i++) {
(*(matrix+i)) = malloc(sizeof(int)*COLUMN);
}
populate_matrix1(array,ROW,COLUMN);
populate_matrix2(matrix,ROW, COLUMN);
print_matrix2(matrix,ROW,COLUMN);
printf("###\n");
print_matrix(array,ROW, COLUMN);
return 0;
}
Output:
Hello World
1 2 3 4
1 3 5 7
1 4 7 10
###
1 2 3 4
1 3 5 7
1 4 7 10
This post will be interactive, I’ll respond to every question under this post regarding pointer arithmetic.