Stéphane Konstantaropoulos said:
int *matrix /* pointer to the start of the matrix */
matrix = malloc(sizeof((*matrix) * 576 * 720)); /* allocate the memory*/
if(matrix == NULL)
exit(1); /* not enough memory */
Use exit(EXIT_FAILURE). exit(1) does not reliably return a failure
indication to the environment. You should also consider whether
immediately terminating the program is too drastic.
/* access the matrix by doing */
matrix[1][1]; /* for example, up to [575][719] */
matrix is a pointer to int.
matrix[1] is an int.
matrix[1][1] is an illegal expression, since matrix[1] is not an array
or pointer.
If your matrix is of a fixed size, known at compilation time, you can
do:
struct my_matrix_type {
int m[576][720];
};
struct my_matrix_type *matrix;
matrix = malloc(sizeof *matrix);
/* check for matrix == NULL */
matrix->m[1][1]; /* refers to an element of the matrix */
(My first attempt didn't wrap the array in a struct; m[1][1] indexed
by matrices rather than by ints. There may be a cleaner way to do
this.)
If it's potentially of dynamic size, you can either allocate a
one-dimensional array and roll your own indexing function, or you can
allocate an array of pointers *and* allocate each of the rows.
You can also allocate the whole array of 576*720 ints, then initialize
the pointers so each one points within the single array.
Details are left as an exercise (either for the OP or for anyone else
who wants to jump in).
[...]
To free your memory:
free(matrix);
matrix = NULL; /* for more safety */
This doesn't give you much more safety. If the value of matrix has
been copied to another variable, that other variable still holds the
invalid pointer value. Once you've free()d matrix, just don't refer
to it. Setting matrix to NULL can help you avoid (or detect) certain
errors, but it's better just not to make those errors in the first
place. (And yes, that's easier said than done.)