0

I must create a large matrix (i.e. 10,000x10,000) with the spine as an array of float pointers:

 typedef float* DynamicMatrix[MAT_SIZE];
 DynamicMatrix matDyn;

Now i must allocate rows and initialize them to zero.

// allocate rows and initialize to 0
    for (r = 0; r < MAT_SIZE; r++) {
        matDyn[r] = new float[MAT_SIZE];
        for (c = 0; c < MAT_SIZE; c++) {
            matDyn[r][c] = 0;
        }
    }

Is my allocation and initialization correct?

What is the difference between allocation an array the way I did above and by saying something like float DynamicMatrix[10,000][10,000]?

tmacnadidas
  • 27
  • 1
  • 2
  • 10
  • Yes, they are. What is your issue? – wjmolina Oct 28 '13 at 18:29
  • @JosuéMolina What is the difference between allocation an array the way I did above and by saying something like float DynamicMatrix[10,000][10,000]? – tmacnadidas Oct 28 '13 at 18:32
  • The difference is that the former allows you to create a jagged array, whereas the latter does not (this is because the former is dynamically-allocated, whereas the latter is not). – wjmolina Oct 28 '13 at 18:36
  • So memory management-wise, a dynamically allocated array would be more efficient than a predefined 2d array? – tmacnadidas Oct 28 '13 at 18:38
  • I would say that, memory-management wise, a statically-allocated array is more "efficient" because it requires no management at all, as this is loaded onto the stack instead of the heap. – wjmolina Oct 28 '13 at 18:41
  • Lets say MAT_SIZE = 100,000. Would it be wise to use a statically-allocated array? Or would I use my system resources better with a dynamic array? – tmacnadidas Oct 28 '13 at 18:47
  • I am just trying to figure out why one would use dynamic arrays – tmacnadidas Oct 28 '13 at 18:47
  • I use dynamic arrays when I do not know their sizes beforehand. – wjmolina Oct 28 '13 at 18:50
  • I recommend you read the following: http://stackoverflow.com/questions/2672085/c-static-array-vs-dynamic-array – wjmolina Oct 28 '13 at 18:52

1 Answers1

0

The declaration

float DynamicMatrix[10000][10000];

declares 10000 x 10000 floats of contiguous storage on the stack. This might be a tall order that your machine may not be able to fulfill in one chunk. For most machines with 4-byte floats that works out to 400 MB of data.

On the other hand, in the array of pointers to vectors approach, each row of data is separately allocated on the heap. This may be easier for the allocator to fulfill. On the other hand, contiguous storage can be very fast in terms of access.

emsr
  • 15,539
  • 6
  • 49
  • 62