# Thread: Question to do with matrices

1. ## Question to do with matrices

When defining a matrix of ints (as in an array of an array), is there a way of predefining every element as zero, or do I have to do it manually using 2 for loops?

Also the size of the matrix will be different everytime i declare it.

Cheers 2. Code:
`int mat = { { 0 } };`
Though some fussy compilers complain at the lack of initialisers, C states that anything which isn't specified is set to zero (of the correct type)
So chars would be '\0', floats and doubles would be 0.0f and 0.0 respectively and pointers would be NULL. 3. Also is there a maximum number of elements an int matrix can hold, I declared an int matrix of size  and the program crashes. 4. Well 1000x1000x4 (typical int size) is 4MB.
Which is a hell of a lot to go on the stack at one go.

The default for VC is either 0.5 or 1MB IIRC.

You can increase this if you want. 5. And of course it is always possible to start using dynamic memory, where there is no such limitation 6. Does that mean using data structures such as Linked lists? 7. Originally Posted by Wiretron
Does that mean using data structures such as Linked lists?
no, they mean using malloc() to allocate memory on the heap (which is larger and it tells you if the memory allocation fails) 8. And you don't need to allocate all matrix at once, you can allocate one row at once and still the get original way to access matrix members... So your matrix can be bigger than biggest non-segmentable memory chunk supported by the current system 9. Ok thanks, I'm going to holding a matrix with possibly up to 1,000,000^2 elements, what are the best methods to holding the matrix, speed of execution, (as in how quickly I can store it and access elements) is a key issue too. 10. Originally Posted by Wiretron
Ok thanks, I'm going to holding a matrix with possibly up to 1,000,000^2 elements,
You'll need a lot of memory and a rather big harddisk for that. something like 4 tera bytes.
K. 11. Hmm lol, maybe not that elements then, but the amount of elements will be substantial, what sort of data structure would be ideal? 12. Is your matrix sparse? (ie. many entries are 0). There are methods for efficient data structures and computations with sparse matrices, just google it (oh the sweet irony, as google relies on *huge* sparse matrix computations to make accomodate your searching needs) 13. Yeah it's sparse. 14. One more tip:

U can also define the array as static or global directly to initialize all elements to 0.

ya, but ur problem do needs a dynamic array. 15. One idea would be to use a tree or summat, eg. divide the matrix into four quadrants, and so on. Access would be a little slower (log n) but on the upside you use only a couple times as much space as is needed.

Or a hash table. More work, but could give even better space usage, down to < 1.25x the number of actual elements used. Popular pages Recent additions 