Reputation: 3321
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 << ", ";
}
Upvotes: 0
Views: 1362
Reputation: 18532
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];
Upvotes: 0
Reputation: 239341
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] << ", ";
}
Upvotes: 3