I have code that looks like
int main(int argc, char *argv[]){
char ***matrix;
matrix = calloc(2, sizeof(char **));
for (int i=0; i<2; i++){
matrix[i] = calloc(ROWS+2, sizeof(char*));
for (int j=0; j<COLS; j++){
matrix[i][j] = malloc(COLS+2);
memset(matrix[i][j], (int)DEFAULT, COLS+2);
}
}
Is there a way to do a similar kind of thing without the use of malloc and calloc? For example, in the case of 1d array I know you can do something like this
unsigned char malloc_data[MAX_SIZE];
size_t malloc_used; /* automatically initialized to zero */
void *stack_malloc(size_t size) {
void *p = &malloc_data[malloc_used];
if(size + malloc_used > MAX_SIZE) return 0; /* out of memory */
malloc_used += size;
return p;
}
OR something like this
static char *allocp = allocbuf[0];
if (allocbuf + ALLOCSIZE - allocp >= n) { /* it fits */
and
if (p >= allocbuf && p < allocbuf + ALLOCSIZE)
I want to try to use stack variables and temps instead of dynamic memory allocated ways. However, when I try to think about how to apply these types of ways to my three dimensional sense, my head starts spinning. Please help clarify things to me
Assuming you want to keep the triple pointer usage, the storage can be allocated on the stack and initialized like this:
char ***matrix;
char **mats_[2];
char *mat_rows_[2][ROWS+2];
char mat_cols_[2][ROWS+2][COLS+2];
matrix = &mats_[0];
for (int i = 0; i < 2; i++) {
matrix[i] = &mat_rows_[i][0];
for (int j = 0; j < ROWS+2; j++) {
matrix[i][j] = &mat_cols_[i][j][0];
memset(matrix[i][j], (int)DEFAULT, COLS+2);
}
}
You could also define matrix
as an array[2] of char **
instead of a single char ***
, which would allow you to eliminate the mats_
variable:
char **matrix[2];
char *mat_rows_[2][ROWS+2];
char mat_cols_[2][ROWS+2][COLS+2];
for (int i = 0; i < 2; i++) {
...
In the comments below, OP asked whether the memset
was necessary. All the elements of mat_cols_[2][ROWS+2][COLS+2]
need to be set to the same value DEFAULT
. If DEFAULT
can be replaced with 0
, this is easy to do by defining mat_cols_
with an initializer with pretty much everything defaulting to 0:
char mat_cols_[2][ROWS+2][COLS+2] = { 0 };
If DEFAULT
cannot be replaced with 0, the only way to do it would be for the initializer to supply values for all the elements explicitly, which has a maintainability problem since the dimensions are defined in terms of the macros ROWS
and COLS
. The GNU C Compiler (GCC) has an extension to the C language designated initializers that allows a range of array elements to be initialized to the same value. That could be used as follows:
char mat_cols_[2][ROWS+2][COLS+2] =
{[0 ... 1] =
{[0 ... ROWS+2-1] =
{[0 ... COLS+2-1] = DEFAULT}
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.