Solved

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

Posted on 2006-06-28
3
362 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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
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.

758 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now