Solved

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

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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
C++ to C# code conversion issue 4 108
computer science syllabus 3 83
What is sub-make ? 2 61
max float value 3 41
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…
Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
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.

810 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