问题描述
我该如何进行涉及数组指针的矩阵乘法?
how do i do matrix multiplication involving pointer to arrays?
void tom::matrixmultiply(void* btr)
{
short* block = (short *)btr;
int c[4][4]={1,1,1,1,2,1,-1,-2,1,-1,-1,1,1,-2,-2,-1};
块是一个4x4矩阵,我希望将其乘以矩阵c
block is a 4x4 matrix and i want it to be multiplied by matrix c
推荐答案
short c[4*4] = ...
如果要使用2个维度数组,则应这样初始化:
If you want to use 2 dimensionnal arrays, you should initialize like that:
short c[4][4] = {
//first row
{ 1, 1, 1 },
//second row
{ 2, 1, -1, -2},
//third row
{ 1, -1, -1, 1 },
//fourth row
{ 1, -2, -2, -1 } };
如果要在函数中使用此固定大小的数组,可以在参数列表中使用固定大小:
If you want to use this fixed size array in a function, you can use the fixed size in the parameter list:
void yourFunction(short mat[4][4])
{
...
}
//or:
void yourFunction2(short (*mat)[4])
{
...
}
但是,如果要使用short*
,则需要使用1维数组:
But if you want to use short*
, then you need to work with 1 dimension array:
short* mat = new short[rows * columns];
for (int i = 0; i < rows; i++)
for (int j = 0; j < columns; j++)
{
mat[i * columns + j] = ...;
}
...
delete [] mat;
对于一维数组,您需要将矩阵的大小保持在某个位置:
With 1 dimension array, you need to keep somewhere the size of your matrix:
void yourFunction(short* mat, int rows, int columns)
{
for (int i = 0; i < rows; i++)
for (int j = 0; j < columns; j++)
{
mat[i * columns + j] = ...;
}
}
回答您的评论有没有办法保持空白* ...
您可以使用typedef
:
Answer to your comment Is there way to keep the void*...
You can use a typedef
:
typedef short (*MATRIX4x4)[4];
void yourFunction(void* ptr)
{
MATRIX4x4 mat = (MATRIX4x4)ptr;
//do whatevet you want
mat[0][0] = ...;
}
void main()
{
short matrix[4][4] = ...;
yourFunction(matrix);
}
但是我不建议使用空指针...
But I don''t recommand using void pointers...
这篇关于矩阵乘法涉及C ++中的数组指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!