指向矩阵

发布于 2024-12-11 16:37:01 字数 245 浏览 0 评论 0原文

我想声明一个指向矩阵并从矩阵检索回值的指针:

float *p;
float ar[3][3];

[..]//give values to ar[][]

p = ar;

//Keep on printing values in the 3 X 3 matrix
for (int i = 0; i < 10; i++)
{
p = p + i;
cout << *p << ", ";
}

I wanted to declare a pointer which would point to a matrix and retrieve a value back from the matrix:

float *p;
float ar[3][3];

[..]//give values to ar[][]

p = ar;

//Keep on printing values in the 3 X 3 matrix
for (int i = 0; i < 10; i++)
{
p = p + i;
cout << *p << ", ";
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

合约呢 2024-12-18 16:37:01

我怀疑你在:

p = &ar[0][0];

也可以写成:

p = ar[0];

虽然你的 for 循环需要使用 p = p + 1; 而不是 p = p +我;


如果您希望循环能够按行和列访问矩阵的成员,您还可以使用指向数组的指针:

float (*p)[3];

p = ar;

for (int i = 0; i < 3; i++)
    for (j = 0; j < 3; j++)
    {
        cout << p[i][j] << ", ";
    }

I suspect that you are after:

p = &ar[0][0];

which can also be written:

p = ar[0];

although your for loop then needs to use p = p + 1; rather than p = p + i;.


You can also use a pointer to an array, if you want your loop to be able to access the members of the matrix by row and column:

float (*p)[3];

p = ar;

for (int i = 0; i < 3; i++)
    for (j = 0; j < 3; j++)
    {
        cout << p[i][j] << ", ";
    }
帅气尐潴 2024-12-18 16:37:01

EDIT2:我是个白痴,我不小心使用了float **matrix而不是float (*matrix)[3]。咖啡馆一直都有正确的答案。

这是你想要的吗?

#include <stdio.h>
#include <stdlib.h>

void print_matrix(float (*matrix)[3], size_t rows, size_t cols)
{
   int i, j;
   for (i = 0; i < rows; i++)
      for (j = 0; j < cols; j++)
         printf("%f ", matrix[i][j]);
}

int main(void)
{
   float ar[][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
   print_matrix(ar, 3, 3);

   return EXIT_SUCCESS;
}

编辑:您还可以:

float *row1, *row2, *row3;
row1 = ar[0];
row2 = ar[1];
row3 = ar[2];
...
float row1_total = row1[0] + row1[1] + row2[2];

EDIT2: I'm an idiot I accidentally had float **matrix instead of float (*matrix)[3]. caf had the right answer all along.

Is this what you want?

#include <stdio.h>
#include <stdlib.h>

void print_matrix(float (*matrix)[3], size_t rows, size_t cols)
{
   int i, j;
   for (i = 0; i < rows; i++)
      for (j = 0; j < cols; j++)
         printf("%f ", matrix[i][j]);
}

int main(void)
{
   float ar[][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
   print_matrix(ar, 3, 3);

   return EXIT_SUCCESS;
}

EDIT: you can also have:

float *row1, *row2, *row3;
row1 = ar[0];
row2 = ar[1];
row3 = ar[2];
...
float row1_total = row1[0] + row1[1] + row2[2];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文