2 Replies - 613 Views - Last Post: 11 March 2009 - 07:25 AM Rate Topic: -----

#1 tetmarie  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 02-March 09

Dynamic Memory Allocation

Post icon  Posted 11 March 2009 - 01:20 AM

We are studying dynamic memory allocation. I am studying the powerpoint slides we were given, but there is this certain code that I can't understand.

#include<stdio.h>
#include<stdlib.h>

float** makeMatrix(int n, int m) { // I don't understand why there are two **
float* memoryPtr;
float** matrixPtr; // Here, there are two again. Howcome?
int i;

memoryPtr=(float*)malloc(n*m*sizeof(float));
matrixPtr=(float**)malloc(n*sizeof(float));

if (memoryPtr==NULL || matrixPtr ==NULL) {
fprintf(stderr, "Not enough memory \n"); //Please explain this line also.
exit(1)

}

for(i=0; i<n, i++, memoryPtr += m) { //Please explain the for loop also.
matrixPtr[i] = memoryPtr;
}

return matrixPtr;
} 



Thank you very much for your help.

Is This A Good Question/Topic? 0
  • +

Replies To: Dynamic Memory Allocation

#2 boblied  Icon User is offline

  • D.I.C Head

Reputation: 8
  • View blog
  • Posts: 66
  • Joined: 20-February 09

Re: Dynamic Memory Allocation

Posted 11 March 2009 - 05:53 AM

The two asterisks will become clear when you understand the for-loop that initializes the variables. It often helps to draw the blocks of memory and the pointers; see below.

The fprintf is because malloc may return a null pointer if there is no memory available. It rarely happens, but it always has to be checked.

In the for-loop, the memory that was allocated is being set up to look like an array. There were two blocks of memory allocated: one to hold enough space for the actual numbers (memoryptr), and one to point to each row of the "array" (matrixPtr).

Here's how it looks for a 2x3 array:

(space for 6 floats)
memoryPtr --> |	|
			  |	|				  (space for 2 row pointers)
			  |	|	  |	  | <-- matrixPtr
			  |	|	  |	  |
			  |	|
			  |	|



After the for loop, each element of of matrixPtr is set to point to the beginning of a row in the block of memory that memoryPtr points to:

(space for 6 floats)
memoryPtr --> |	|<-------
			  |	|		\		(space for 2 row pointers)
			  |	|	  |	  | <-- matrixPtr
			  |	|<-----|	  |
			  |	|
			  |	|



Now it should be more apparent that matrixPtr is a pointer to some pointers; *matrixPtr is a pointer to a float; and to get to the float that it points to, you need to dereference the pointer again. That's why it's declared as **.
Was This Post Helpful? 0
  • +
  • -

#3 tetmarie  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 02-March 09

Re: Dynamic Memory Allocation

Posted 11 March 2009 - 07:25 AM

So, you mean that *matrix ptr is a pointer to a pointer...that's why it has two astericks?

Thanks so much. I just really want this to be clear.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1