I made a function that returns a pointer to a newly created matrix. Now I want this function to return an error code of type status_t instead of the pointer. To do this, another pointer level has to be added and the matrix has to be returned by reference. However, I can't understand why a segmentation error appears. Here is part of my working code (a) and my failed attempt (b):
(a)
int **create_matrix(size_t dimension) {
int **p;
size_t e;
size_t h;
if (dimension == 0)
return NULL;
for (h = 0; h < dimension; ++h) {
if ((p[h] = malloc(dimension * sizeof(int))) == NULL) {
for (e = h; e >= 0; --e) {
free(p[e]);
p[e] = NULL;
} <-------- missing closing brace
return NULL;
}
}
return p;
}
(b)
status_t create_matrix(size_t dimension, int ***p) {
size_t e;
size_t h;
if (p == NULL)
return ERROR_NULL_POINTER;
for (h = 0; h < dimension; ++h) {
if (((*p)[h] = malloc(dimension * sizeof(int))) == NULL) {
for (e = h; e >= 0; --e) {
free((*p)[e]);
(*p)[e] = NULL;
} <-------- missing closing brace
return ERROR_NO_MEMORY;
}
}
}
thanks!
free()when you create a matrix?