I am using Eclipse on a 32-bit Ubuntu virtual machine to work on a project. I have a big problem when trying to implement a structure or just when trying to run a specific function. The function is this one:
int count (matrix m, int v[], int w[], int col) {
int r=0;
int j=0;
while (j < m.length) {
int k=0;
bool aux=true;
while (k < col && aux ){
if (v[k] == 1) {
if(m.i[j][k] != w[k])
aux=false;
}
k++;
}
if(aux) r++;
j++;
}
return r;
}
This function receives a matrix (defined below), a vector with ones and zeros (to learn which columns to search, a vector with the values we want to search in those columns and also the number of columns (equal to the length of the vectors and matrix). When it strikes the second “if” it gives me Segmentation Fault (I cannot understand what it is), and I can see that it is not correct to define it that way, but I have tried and tried and I can’t seem to find a way to access the values in the vector. Here follows my struct matrix:
typedef int *ind;
struct matrix {
ind *i;
int length;
};
typedef struct matrix matrix;
In this structure my matrix has a pointer and the length (number of lines); the pointer goes to a vector of pointers (one pointer for each line) and each one of those pointers go to a vector that is, in fact, my line of the matrix. Here go my functions to add and create an empty matrix:
matrix emptyS(int n, int col) {
matrix m;
int d=0;
m.length=0;
m.i=(ind*) malloc(sizeof(int)*n);
int x;
for (x=0; x < n; x++)
{
*m.i = (int*) malloc(sizeof(int)*col);
}
while (d<n){
m.i[d]=NULL;
d++;
}
return m;
} /*Updated*/
matrix add(matrix m,int v[]){
m.i[m.length+1]=v;
m.length++;
return m;
}
I know this is a very specific question but I have been going crazy changing my functions and cannot seem to be successful.
Your definition of
iis this:You have the following definition of
ind:This means that your definition of
ireally is this:Which is a pointer to a pointer, this means you have to allocated your memory incorrectly.
This allocation is only for a
int*, but what about the second pointer? You’ve never allocated any memory for it!Allocate the rows of the matrix, something like this:
EDIT
Your code after you do your allocation for your matrix, sets your pointers in the matrix to
NULL, essentially leaving all the memory you just allocated dangling, with nothing pointing to it!!You should not set it to
NULL, but instead you should write stuff in your matrix you just allocated memory for.