矩阵乘法涉及C ++中的数组指针 [英] matrix multiplication involving pointers to arrays in c++

查看:96
本文介绍了矩阵乘法涉及C ++中的数组指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何进行涉及数组指针的矩阵乘法?

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*转换为void*,然后将void*转换回short*是可以的.但是您拥有的是二维数组:short*[].

我建议您这样声明矩阵:
Your casting is not valid. Casting short* to void*, and void* back to short* is OK. But what you have is a 2-dimensions array: short*[].

I suggest that you declare your matrix like that:
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 ++中的数组指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆