Reputation: 82
i'm having a problem when trying to write the second row of the matrix (segfault exc_bad_access
and kern_invalid_address
) allocated with the following function:
Here is my alloc function:
int amatrix(char*** m, const int i, const int j)
{
int k;
(*m) = (char**) malloc(sizeof(char*) * i);
if ((*m) == NULL) {
return ERROR;
}
for (k = 0; k < i; k++) {
(*m)[k] = (char*) malloc(sizeof(char) * j);
if ((*m)[k] == NULL) {
return ERROR;
}
}
return SUCCESS;
}
I call it by using:
char** matrix;
if (amatrix(&matrix, i, j)) { ...
Edit: As requested:
#define ERROR 00
#define SUCCESS 01
The access where the trouble is:
int gmatrix(char*** m, const int i, const int j)
{
int k, l;
for (k = 0; k < i; k++) {
for (l = 0; l < j; l++) {
printf("Matrix[%d][%d] = ", k, l);
scanf(" %c", m[k][l]);
}
}
return SUCCESS;
}
Thank you for the quick replies!
Upvotes: 2
Views: 124
Reputation: 110202
Your gmatrix
function should take m
as a char**
parameter, not char***
, because it does not need to change its value like amatrix
does (only what it points to).
Then you should change the scanf call to:
scanf(" %c", &m[k][l]);
Your current code (with char*** m
) doesn't work because m[k]
will give undefined behavior when k!=0
, because m
points only to a single char**
.
If m
is a char***
, the scanf call would need to look like:
scanf(" %c", &(*m)[k][l]);
Upvotes: 2