This question is not a duplicate. I didn't find a solution in the question linked above
Using void* pointers, I wrote a function that prints out the elements of an array of any datatype. Basically, it accepts as parameters:
- a void* pointer (i.e. the array to print).
- the size of individual elements within the array.
- the array length.
- a pointer to a void function that accepts only a void* pointer as parameter which stores the address of the element of the array.
void printArray (void* pointer, int width, int numberOfElements, void (*functionPointer)(const void*))
{
for (int i = 0; i < numberOfElements; i++)
{
functionPointer ((void*)(pointer + width*i));
}
}
Then, I created different functions that print out a single variable; here, one of these:
void printInt (const void* v)
{
int* myInt = (int*) v;
printf ("%d ", *myInt);
}
What is left to do is to pass to printArray() the name of the print function I want to use, so that it can be generic. Below an example:
int tempArray [] = {0,1,2};
printArray (tempArray, sizeof (int), 3, printInt);
In order to print a 2d array, I've thought to put the "printArray" function in a for loop, considering every row of the matrix like a single array. To do so, I created this function, changing the void* pointer to a void** pointer and replacing the variable that stores the number of elements with the number of rows and cols of the matrix:
void printMatrix (void** pointer, int width, int rows, int cols, void (*functionPointer)(const void* v))
{
for (int i = 0; i < rows; i++)
{
printArray ((pointer + i*width), width, cols, functionPointer);
printf ("\n");
}
}
Here, the main function:
#include <stdio.h>
#define ROWS 8
#define COLS 3
int main ()
{
int matrix [ROWS][COLS] = {
{0, 1, 2},
{3, 4, 5},
{6, 7, 8},
{0, 3, 6},
{1, 4, 7},
{2, 5, 8},
{0, 4, 8},
{2, 4, 6}
};
printMatrix (matrix, sizeof (int), ROWS, COLS, printInt);
return EXIT_SUCCESS;
}
The output:
0 1 2
4 5 6
8 0 3
1 4 7
5 8 0
8 2 4
57 8 2
0 2 0
I'm trying to understand where the problem is. How can I solve it?
EDIT
First of all, thank you everybody for answering. I solved the problem replacing the pointer + i*width
in printArray ((pointer + i*width), width, cols, functionPointer);
with pointer + i*cols
, in this way:
for (int i = 0; i < rows; i++)
{
printArray ((pointer + i*cols), width, cols, functionPointer);
printf ("\n");
}
The printMatrix () function now works correctly.