Solved

How to create a user defined varible length array in ANSI C++?

Posted on 2006-06-28
3
366 Views
Last Modified: 2010-04-01
So,  this should be a real easy answer for a programming guru... worth 500 points.

How do you code a user defined varible length array in C++?

Please provide me with a code example...

(I'm not a programmer.)

Feel free to ask questions if I'm being unclear!

Thanks all!

Gerhard
0
Comment
Question by:gerhardub
  • 2
3 Comments
 
LVL 14

Accepted Solution

by:
wayside earned 500 total points
ID: 17002128
1)

int length = 25; // get length from user somehow
int *pArray = new int[length];
for (int i=0; i<length; i++) {
   pArray[i] = i; // do something here
}

2) use the STL vector class, it handles all the size issues.

0
 
LVL 14

Expert Comment

by:wayside
ID: 17002524
Don't forget to

delete [] pArray;

when you are done with it or you create a memory leak.
0
 
LVL 30

Expert Comment

by:Axter
ID: 17002700
Hi gerhardub,
FYI:
If you create the array with an empty bracket (), the array gets initialized to zero.
Example:
int *pArray = new int[length]();


David Maisonave (Axter)
Cheers!
0

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

713 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question