You are here:

C++/Array expansion


Greetings David-

I'm doing biostatistical work which requires that I translate a MATLAB script into C. This is mostly straightforward but there is one problem (don't worry, it's not related to MATLAB). The MATLAB code returns a matrix, 'decel[m][3]', showing all of the heart rate decelerations for a certain period of time. This matrix always has three columns but a variable number 'm' of rows (from just a couple of dozen on up possibly into the hundreds of thousands).

I am using C's standard array routines and initially storing the data in a double vector, 'cdecel[3*m]'. Then at the end of the program I loop through this vector and convert it into a MATLAB-compatible matrix. I can control the size of this final matrix by simply initializing it to 'm' by 3, but the problem is that I need a way to resize the original 'cdecel' vector as 'm' increases. For memory reasons I don't want to have to initialize it to a length of several million elements (also, as the research progresses, even several million may not be sufficient). In the past I've worked with Java collections which are initialized to 100 elements, and every time the collection fills up, they are resized. Is it possible to do the same in C?

(I'm working in Visual C++ 6 on a machine running Win2k Pro.)

Thank you for your time.

Victor , Thank you for your question.

I am assuming you are using the Standard Template Libary (STL), since you used the word "vector" which is one of the STL container types.

Yes, vectors can be reallocated at any time. You can append to a vector (initially of length 0) using the push_back function. I recommend writing a test program that does this millions of times, so you can verify that the execution time is reasonable. (If not, you can write C++ code (or have my code) to reallocate dynamic arrays in chunks of a specified, fixed size.)

David Spector


All Answers

Answers by Expert:

Ask Experts


David Spector


Highly knowledgeable in the C++ language, Visual C++ (MSVC), Windows API, documentation and other quality-assurance techniques, and debugging. Knowledgeable in MFC, COM, GUI design, and object-oriented design.


I have been a software engineer since 1965. I have been published. My specializations have been: biomedical programming, compiler implementation, and many kinds of Windows programming. I don't do Databases or other business-oriented stuff.

Windows?/DOS Developer's Journal, ACM SIGPLAN Notices, and Computer Science Press.

ICCP Systems Programming Certification
Master's degree equivalent in Computer Science

©2017 All rights reserved.