Making a 2d array (matrix) in a struct

This is a discussion on Making a 2d array (matrix) in a struct within the C Programming forums, part of the General Programming Boards category; If I'm trying to make a 2d array in a struct, do I have to make the struct a certain ...

I'm trying to understand this code, but some of it doesn't make sense to me.

Code:

mat = malloc(rows*sizeof(int*));

How do you know that you're supposed to do sizeof(int*)?
If I understand it correctly, you're just multiplying rows x the "sizeof" a column?

**mat is a pointer (to a pointer), with no memory allocated.

You need to set "rows" to a definate value, obviously, eg, 50. Then:mat = malloc(rows*sizeof(int*))
This allocates enough space for 50 int pointers. The reason we need int pointers is because each first dimension element of mat will also be a pointer (to an actual array of ints) -- that's why mat is a "pointer to a pointer". This parallels the fact that it makes no sense to refer to a matrix value, mat[11] -- however, you can refer to the 11th row. And (to reiterate), in the code, mat[11] is literally a pointer to a 1 dimensional array of ints (ie, a row in your matrix).

Next, each of those 50 row pointers needs space for an actual row. The length of the row is determined by the number of columns (say 30). for (i=0;i<rows;i++) mat[i] = malloc(cols*sizeof(int));
That's why we use (int) here but (int*) previously.

Seems a bit complicated just for a 2D matrix, doesn't it (this is why C is considered "low level" -- it must attend to a lot of fine details). Why can't you just go:

mat = malloc(rows*cols*sizeof(int));

You can. That's all the same you need for 1000 (rows*cols, if rows is 50 and cols 20) ints. The problem is, that will be a one dimensional array of 1000, like:

int array[1000]

which you could use both to store a matrix, but you will keep having to do some weird math in order to find your elements. That's awkward for the programmer and most likely less optimal for the compiler as well.

Not to say it never happens, but they are not considered good style, and WRT matrices, no matter how many dimensions to your matrix (mat[10][10][10][10]), none of them will contain a *** -- you will just get layers of **. I'll leave you to think about why.

What is the type of **mat
*mat
mat

Are they all int's?

int **mat is a pointer to an int pointer.
int *mat is an int pointer.
int mat is just an int.

None of them has to involve an array, eg:

Code:

int mat, *p = &mat, *p2 = &p;

"Pointers to pointers" are also used to pass the address of a pointer to a function so that it can be reassigned:

A pointer is just like any other variable. It holds a value. Everything in C holds a value. Everything. Some values are characters, some are numbers, some are addresses. If it's a pointer, it's holding an 'address of variable type N' as its value.