understanding dynamic matrix declaration

Dear all,
It's been a long time that I haven't done C and I've forgot almost all about it. I'm trying to catch up with it!
Well, first I need to understand one part i.e. dynamic matrix declaration; specifically, I am trying to understand these lines of code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 0. write Data matrix
	int size_x = 210;
	int size_y = 7;
	double **Data, *pDataData;
	Data = (double **)malloc(size_x*sizeof(double *)+size_x*size_y*sizeof(double));
	for (i = 0, pDataData = (double *)(Data+size_x); i < size_x; i++, pDataData += size_y)
	Data[i]=pDataData;

	for(i=0;i<size_x;i++)
		for(j=0;j<size_y;j++){
			Data[i][j] = *(Data_in+size_y*i+j);
			//printf("%f        ", Data[i][j]);
		}	//printf("\n\n\n\n\n");
 

Especially, I have problem understanding the bold lines. Could you try to explain it in a very clear way what exactly is going on here. I mean I know (by book) what malloc does and all that I just don't understand the details like what this initialization does: pDataData = (double *)(Data+size_x) and how a pointer to pointer equals a pointer in this line: Data[i]=pDataData

Thank you very much in advance
Elnaz
Last edited on
Let's assume a 2x3 matrix, sizeof(double) = 8, sizeof(double*) = 4.

Line 5 allocates 2*4+2*3*8 bytes for your matrix.
The first 2*4 bytes are intended for pointer to rows of the matrix.
The rest are for the matrix itself.
That way Data[i] would return a pointer to i'th row and Data[i][j] would return j'th element in that row.

The purpose of lines 6, 7 is to assign the addresses of the rows to the pointers.
Data+size_x is where the first row is. Type of Data is double** and type of pDataData is double*, so you need to cast. Then you assign pDataData, which points to the first row to Data[0], which is supposed to do that. Then you add size_y to pDataData so that it points to the other row and repeat.

whoops. where I said 'row' I should have said 'column'
Topic archived. No new replies allowed.