Trying to write a matrix-multiplying function for arbitrary-sized matrices in C. I’m trying the following for my function signature:
void matrixMult(void *A, int Xa, int Ya, void *B, int Xb, int Yb);
(it’s returning void for now while I troubleshoot it, I’ll make a proper return later once I have it working the way I want it to)
The X and Y parameters are intended to inform the function of the dimensions of the incoming arrays (from my understanding, that’s necessary, since in C arrays don’t know their own size). So I’m passing in two void pointers A and B, as well as their dimensions.
My question: Once I’m in the function, how do I go about casting the void pointers back to int arrays so I can read them? I tried the following:
(int)*A[someX][someY]
, but I get a compiler error about “invalid use of void pointer”.
EDIT
The following is my full function for now (updating as I’m troubleshooting it):
#pragma warning(disable: 8057)
#include <stdio.h>
void matrixMult(int **A, int Xa, int Ya, int **B, int Xb, int Yb);
int main(int argc, char *argv[]) {
// [x][y] x--> row; y-->cols
int a[3][5] = {
{ 1, 2, 3, 4, 5 }
, { 10, 20, 30, 40, 50 }
, { 4, 8, 15, 16, 23 }
};
int b[5][7] = {
{ 1, 2, 3, 4, 5, 6, 7 }
, { 10, 20, 30, 40, 50, 60, 70 }
, { 4, 8, 15, 16, 23, 42, 0 }
, { 1, 2, 3, 4, 5, 6, 7 }
, { 10, 20, 30, 40, 50, 60, 70 }
};
matrixMult((int **)a, 3, 5, (int **)b, 5, 7);
printf("done\n");
return 0;
}
void matrixMult(int **A, int Xa, int Ya, int **B, int Xb, int Yb) {
printf("starting matrix mult\n");
int i, j;
for (i=0; i<Xa; i++) {
for (j=0; j<Ya; j++) {
//printf("%i, %i:\t", i, j);
printf("%i\t", A[Ya*i+j]);
}
printf("\n");
}
}
EDIT 2 Thanks for the tips and resources guys! The version posted above works as I expect it to now, but I’m afraid it’s an ugly bastardization of how pointers are SUPPOSED to be used. For now I’m off to do some more reading on pointers (thanks cnicutar!), and I’ll revisit this later. Any further criticism of my latest version is appreciated, but I’m marking this answered and moving on to do some further reading for now. Thanks again!
If I understand you question correctly you could do something like
Why are you using
void *and notint **Astraight away ?EDIT 1
In light of comment below: see this FAQ entry (
f3is what you want). And also this one.Edit 2
Declare and initialize them (something) like this: