little question about dynamic length arrays

Started by
26 comments, last by Sneftel 16 years, 2 months ago
As far as I know, it's not possible to create arrays with a dynamic length on the stack in C++. So, can you tell me why does the following code work? (I'm using the MinGW compiler) int dynamicLength = 0; for (int i = 0; i < 5; ++i) { dynamicLength += i; } float numbers[dynamicLength]; numbers[0] = 5.5; numbers[1] = 10.1; ... thanks
Advertisement
Edit: re-read, rethought answer..
It may be a GNU extension. Most of the common compilers extend the language in various ways, but these are non-standard and typically not portable.
The code works because your compiler compiles it, whereas my compiler doesn't allow it and won't compile it. Technically my compiler is exhibiting the expected behaviour as the above code isn't standard C++ and so is not portable.
Sorry for the noob question, but what does it exactly mean that the code is not portable? Should i use new and delete instead?
It means that if you try compile the code under a different compiler, say the Intel compiler or the Microsoft one, it may or may not compile. The code is non-standard, so a standards compliant compiler may reject it.

The most reasonable alternative is to use std::vector.
#include <vector>#include <iterator>#include <algorithm>int main(){   std::vector<float> numbers;   numbers.push_back(5.5);   numbers.push_back(10.1);   // ...   for( int i = 0 ; i < numbers.size() ; ++i )   {      std::cout << numbers << '\n';   }   // or if you want to get into fancy one-liners:   std::copy(numbers.begin(),numbers.end(),std::ostream_iterator<float>(std::cout, "\n"));}


Nicest of all, std::vector both remembers it's size (so you don't need a separate variable), it preallocates memory (insertions are reasonably efficient) and it cleans up after itself (no need to remember to use delete [] ).
Ok, thank you for your quick answers.
Not portable means that this code won't work on each and every C++ compiler. However, the gcc compiler exists probably on every platform and as such the code is reasonable (GNU C++ extensions can be very useful) even if cross-platform compatibilty is required. If compiler independence is required, you could still use dynamic arrays if they are supported with a few preprocessor macros or even use _alloca or some such.
Quote:Original post by rip-off
The most reasonable alternative is to use std::vector.


But... dynamic arrays are faster!! (Sorry, whenever I see std::vector on the stack I just think "FFS! add sp, cx" :P)

Edit: doh

[Edited by - Konfusius on February 3, 2008 10:44:15 AM]
Quote:Original post by Konfusius
Quote:Original post by rip-off
The most reasonable alternative is to use std::vector.


But... dynamic arrays are faster!! (Sorry, whenever I see std::vector on the stack I just think "FFS! add bp, cx" :P)

Huh? A vector is a dynamic array.

This topic is closed to new replies.

Advertisement