Array declared correctly?

S

spasmous2

I have some working C++ code that (stripping out extraneous code) does
the following:


int main(int argc, char *argv[])
{
DcmFileFormat dcm[argc];


....
}

The code compiles without complaint with -Wall on and appears to
execute fine with different argc values. However coming from a C
background, I'm wondering if this is valid C++ and whether the memory
needs to be "freed" at the end? I vaguely recall new and delete
operators in C++ but don't know if they're relevant in this case.

I apologize for my naive question. I hope someone can help - thanks!
 
I

Ian Collins

spasmous2 said:
I have some working C++ code that (stripping out extraneous code) does
the following:


int main(int argc, char *argv[])
{
DcmFileFormat dcm[argc];


....
}

The code compiles without complaint with -Wall on and appears to
execute fine with different argc values. However coming from a C
background, I'm wondering if this is valid C++ and whether the memory
needs to be "freed" at the end? I vaguely recall new and delete
operators in C++ but don't know if they're relevant in this case.
No, it is using a gcc extension. C++ does not have C's Variable Length
Arrays.

Look at using std::vector instead of a dynamic array.
 
J

James Kanze

I have some working C++ code that (stripping out extraneous
code) does the following:
int main(int argc, char *argv[])
{
DcmFileFormat dcm[argc];

The code compiles without complaint with -Wall on and appears
to execute fine with different argc values. However coming
from a C background, I'm wondering if this is valid C++ and
whether the memory needs to be "freed" at the end? I vaguely
recall new and delete operators in C++ but don't know if
they're relevant in this case.

It's neither valid C++, nor valid C90; it's an extension which
was added to C99 (and won't be picked up by C++0x).

It doesn't compile for me, with any of the compilers I have
available (g++, Sun CC and VC++): g++ says:

vla.cc: In function 'int main(int, char**)':
vla.cc:11: error: ISO C++ forbids variable-size array 'v'

(This is invoking it with my usual options: -std=c++98 -pedantic
.... The -pedantic seems to be the key one here. All of the
other compilers reject it out of the box.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,164
Messages
2,570,898
Members
47,439
Latest member
shasuze

Latest Threads

Top