Pass matrix by reference using pointer of pointer

Hello, i really don't know why has a error in my code, that pass a pointer of pointer (name of a matrix with 2 dimensions). Here is the source code of a simple example where appears segmentation fault when execute (but compiles normal):

#include <stdio.h>

#define LINHAS 3
#define COLUNAS 5

float a[LINHAS][COLUNAS];

void zeros(float **p,float m, float n){
int i,j;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
p[i][j]=0;
}

void exibe(float **p,float m, float n){
int i,j;
for(i=0;i<m;i++){
for(j=0;j<n;j++)
printf("%f ",p[i][j]);
printf("\n");
}
}

int main(int argc, char **argv){
float **ptr_a = (float**)a;
zeros(ptr_a,LINHAS,COLUNAS);
exibe(ptr_a,LINHAS,COLUNAS);
return 0;
}
Last edited on
float ** ptr_a = ...
Dereferencing a pointer to a pointer will return a pointer.
The type of ptr_a[i] is thus float *.
However, that memory location does not have a pointer, and that
dereference does not return the address &a[i][0].

Second. Float indices (m, n)? No, please.

How about:
1
2
void zeros( float p[][COLUNAS], int m, int n);
void exibe( float p[][COLUNAS], int m, int n);
Então temos um BR/PT no fórum? Achei que estava sozinho.
iQChange, sou Brasileiro sim :D

keskiverto, isn't interesting to me use functions like you suggested, because the number of columns can change, like a function to multiply matrices. However, i use a declaration of matrix in this way: int a[LINHAS*COLUNAS], so i can pass a pointer as parameter and manipulate.

Thank you.
the number of columns can change

That was not apparent from your example, which was using statically allocated 'a' (although only the dynamically determined m*n block of it).

You seem to be using C. C supports VLA and pointer to array. See
http://collaboration.cmc.ec.gc.ca/science/rpn/biblio/ddj/Website/articles/CUJ/2002/0201/meyers/meyers.htm
(particularly Listing 3)
@cadubentzen You have PM deactivated. If you activate it, we can talk about C++ stuff ;)
It works:

#include <stdio.h>
using namespace std;
#define LINHAS 3
#define COLUNAS 5

float a[LINHAS][COLUNAS];

void zeros(float **p, short m, short n) {
short i, j;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
p[i][j] = 0;
}

void exibe(float **p, float m, float n) {
int i, j;
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++)
printf("%f ", p[i][j]);
printf("\n");
}
}

int main(int argc, char **argv) {

float **ptr_a = new float* [LINHAS];
for (int i = 0; i < LINHAS; i++) {
ptr_a[i] = new float[COLUNAS];
}

zeros(ptr_a, LINHAS, COLUNAS);
exibe(ptr_a, LINHAS, COLUNAS);

for(int i = 0; i < LINHAS; i++){
delete [] ptr_a[i]; //deleting pointers ptr_a[i]
}
delete [] ptr_a; //deleting pointer ptr_a

return 0;
}
Last edited on
Topic archived. No new replies allowed.