Solved

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

Posted on 2006-06-28
3
367 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

738 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