|
The easiest way is to use std::vector class and just call its push_back member. Take a look at this article[^] for a quick tutorial.
My programming blahblahblah blog. If you ever find anything useful here, please let me know to remove it.
|
|
|
|
|
As has been said previously using std::vector is the best and easiest way of doing this. But you also said you are a beginner starting to learn C++ and perhaps you want to learn how to do it yourself. What you have to do in that case allocate a certain amount of memory, the amount does not matter, and when you use up all that memory you will have to reallocate another larger block, move all your data to the new block, delete the old one, have your original pointer point to the new one and continue on.
#include <iostream>
using namespace std;
void main()
{
int *pointer = NULL;
int size = 0;
int nextindex = 0;
int growby = 10;
int number = 0;
cin >> number;
while (number > 0)
{
if (nextindex >= size)
{
cout << "Allocating more memory" << endl;
int *newpointer = new int[size + growby];
memset (newpointer, 0, (size + growby) * sizeof(newpointer[0]));
memmove (newpointer, pointer, size * sizeof(pointer[0]));
delete[] pointer;
pointer = newpointer;
size += growby;
}
pointer[nextindex++] = number;
cin >> number;
}
for (int count = 0; count < nextindex; ++count)
{
cout << pointer[count] << endl;
}
delete[] pointer;
} This is the basic technique used by all dynamic array classes such as std::vector, CArray, etc.
"You're obviously a superstar." - Christian Graus about me - 12 Feb '03
"Obviously ??? You're definitely a superstar!!!" - mYkel - 21 Jun '04
"There's not enough blatant self-congratulatory backslapping in the world today..." - HumblePie - 21 Jun '05
Within you lies the power for good - Use it!
|
|
|
|
|
This is a very helpful one. Thanks!!!
Here is what I have so far for the program that reads some (no one knows how many before hand) positive numbers (double) from teh stdin, sorts teh numbers and prints them in sorting orders (biggest number first). Whenever teh number is negative my code should start sort the numbers it already gets (except the negative) and print. I am thinking that it should work, but does anyone see any bugs?
#include <iostream>
#include <cstdlib>
using namespace std;
double *getDouble(int & numbersRead)
{
int arraySize = 0;
double inputVal;
double *array = NULL;
numbersRead = 0;
cout << "Enter any number of integers: ";
while( cin >> inputVal )
{
if(numbersRead == arraySize)
{
double *original = array;
array = new double [arraySize * 2 + 1];
for(int i = 0; i < arraySize; i++)
array[i] = original[i];
delete[]original;
arraySize = arraySize * 2 + 1;
}
array[numbersRead++] = inputVal;
}
return array;
}
int main()
{
double *array;
int size;
array = getDouble(size);
int last = size - 2;
int isChanged = 1;
while(last >= 0 && isChanged)
{
isChanged = 0;
for(int k = 0; k <= last; k++)
{
if(array[k] < array[k+1]
{
double temp;
temp = array[k];
array[k] = array[k+1];
array[k+1] = temp;
isChanged = 1;
}
last--;
}}
for(int i = 0; i < size; i++)
{
if(array[i] < 0)
cout << array[i] << endl;
}
return ;
}
|
|
|
|
|
PJ Arends wrote:
This is the basic technique used by all dynamic array classes
Good heavens. What happened to good ol' realloc? You don't have do the memmove then, right? And isn't calling delete[] pointer the wrong thing to do, because that can actually call the destructors on the items in the array? IIRC, I've seen this behavior stepping into the assembly code ages ago in my C++ days.
Marc
My website
Traceract
Understanding Simple Data Binding
Diary Of A CEO - Preface
|
|
|
|
|
I did say "the basic technique" not "the code" and the code was supplied as an example only.
The memory was allocated with new not malloc so I could not tell a begginer to use realloc on that pointer. int does not have a d'tor so they are not a problem.
The OP is a beginner, he asked about how to allocate a dynamic array when he did not know the size ahead of time. The example code I provided is a very simple way to do it that should be very clear to a beginner. I could have posted the code used by std::vector (or told him to read the vector header file) which you would have had a harder time criticizing, but it would not be very helpful as an example. Or were you so good at coding when you started that you took all those kind of things into consideration when you first learned about arrays and linked lists etc? No? I didn't think so.
"You're obviously a superstar." - Christian Graus about me - 12 Feb '03
"Obviously ??? You're definitely a superstar!!!" - mYkel - 21 Jun '04
"There's not enough blatant self-congratulatory backslapping in the world today..." - HumblePie - 21 Jun '05
Within you lies the power for good - Use it!
|
|
|
|
|
PJ Arends wrote:
I did say "the basic technique" not "the code" and the code was supplied as an example only.
Oops, sorry, I didn't mean to criticize. I was actually intending to ask about the practice of realloc and delete[] because it's been so long since I've used C++. In my posting haste I came off sounding critical, which wasn't what I meant.
Marc
My website
Traceract
Understanding Simple Data Binding
Diary Of A CEO - Preface
|
|
|
|
|
Marc Clifton wrote:
sorry, I didn't mean to criticize
Ok, thanks. I guess I over reacted too, sorry about that.
"You're obviously a superstar." - Christian Graus about me - 12 Feb '03
"Obviously ??? You're definitely a superstar!!!" - mYkel - 21 Jun '04
"There's not enough blatant self-congratulatory backslapping in the world today..." - HumblePie - 21 Jun '05
Within you lies the power for good - Use it!
|
|
|
|
|
Marc Clifton wrote:
realloc
It's C, you shouldn't use it in C++.
Christian Graus - Microsoft MVP - C++
|
|
|
|
|
|
Yeah, I know what you mean, I've recently taken my first C++ project in 2 years. I'm loving it, but it's a steep curve at first.
BTW, I downloaded and read your XAML article. I think I'll get it better when I actually use it a bit though.
Christian Graus - Microsoft MVP - C++
|
|
|
|
|
Marc Clifton wrote:
What happened to good ol' realloc?
It is good only for POD types. In this case it would work, but if you have real objects, their destructors would have never been called. Here is a link to BS's FAQ explaining the matter:
Why doesn't C++ have an equivalent to realloc()?[^]
Marc Clifton wrote:
And isn't calling delete[] pointer the wrong thing to do, because that can actually call the destructors on the items in the array
That's exactly why it is a right thing to do - you want your destructors being called before the objects are destroyed - that's the whole point of having them.
My programming blahblahblah blog. If you ever find anything useful here, please let me know to remove it.
|
|
|
|
|
PJ Arends wrote:
As has been said previously using std::vector is the best and easiest way of doing this. But you also said you are a beginner starting to learn C++ and perhaps you want to learn how to do it yourself.
Generally, these days most C++ "gurus" advise to learn how to use Standard Library first, and only then mess with pointers. That's the approach from Koenig's Accelerated C++[^] and also the latest edition of Lippman's C++ Primer[^]
My programming blahblahblah blog. If you ever find anything useful here, please let me know to remove it.
|
|
|
|
|
Hi guys!
I see that most of people here are very smart programmer so my question may seem like a silly one but keep in mind that I am just started to learn C++.
I am writing a sorting program using dynamically allocated array. I know how to write a program when the size of the array is known. Well, this time I don't know the size of it. My program suppose to read the positive numbers from the keyboard and it need to quit only when i hit ^C. How do you declare your array and populate it when you don't know the size?!
I know that I should use something like this:
int *pointer;
int size;
pointer = new int [size];
but when I go to my for loop what do I say my size should be?
Any help would be greatly appriciated!!!!
Sveta
-- modified at 14:36 Sunday 11th September, 2005
|
|
|
|
|
|
Trollslayer wrote:
You might care to post this in the Visual C++[^] forum.
what? no axe swinging? I guess I need to go back to playing BloodRayne 2, no excitement here....
_________________________
Asu no koto o ieba, tenjo de nezumi ga warau.
Talk about things of tomorrow and the mice in the ceiling laugh. (Japanese Proverb)
|
|
|
|
|
|
Ummmmmmm. I am not even going to hazard a guess what that means ...
|
|
|
|
|
|
Marc Clifton wrote:
Trollslayer wrote:
The "No programming questions please." wasn't big enough...
Actually, it appears to have disappeared. Or at least, I can't see it. Hmmm....
Yes, in fact it is "Please do NOT post programming questions or ads to this forum.". Maybe too long and confusing sentence?
Never forget: "Stay kul and happy" (I.A.)
David's thoughts / dnhsoftware.org / MyHTMLTidy
|
|
|
|
|
dnh wrote:
Yes, in fact it is "Please do NOT post programming questions or ads to this forum.". Maybe too long and confusing sentence?
Oh, I see it now!
Posting Guideline: The Lounge is rated PG. If you're about to post something you wouldn't want your kid sister to read then don't post it. * Do not post programming questions (use the programming forums for that) and please don't post ads.
I stopped reading that paragraph where I placed the "*", thinking the rest of the paragraph was more rambling about PG and kid sisters. It used to be more obvious, IIRC.
Oh well. I'm blind. I admit it.
Marc
My website
Traceract
Understanding Simple Data Binding
Diary Of A CEO - Preface
|
|
|
|
|
Marc Clifton wrote:
I stopped reading that paragraph where I placed the "*", thinking the rest of the paragraph was more rambling about PG and kid sisters.
hmm maybe that's the reason why people post programming questions?
Never forget: "Stay kul and happy" (I.A.)
David's thoughts / dnhsoftware.org / MyHTMLTidy
|
|
|
|
|
Sveta80 wrote:
I know that I should use something like this:
Actually, you should be using C# so you can write:
ArrayList myChars=new ArrayList();
...
myChars.Add(myKeyboardChar);
Isn't that so much simpler than pointers and constructors and destructors and malloc and realloc and STL and...(errr, oops!).
Marc
My website
Traceract
Understanding Simple Data Binding
Diary Of A CEO - Preface
|
|
|
|
|
Or alternatively in C++
vector<char> myChars;
...
myChars.push_back(myKeyboardChar);
I can see how much more complex the C++ solution is over
C# here.
It is a fact that there are almost not circumstances when
it is necessary to use new and delete in C++ anymore,
it is almost always better to use a Standard library
container, which handles all that stuff for you.
However, Microsoft's secret plan to replace C++ with
C# is that they make these containers very hard to use
within the debugger. Debugging support of the STL really
blows in VS 2003. Has anybody tried it out in VS 2005?
|
|
|
|
|
nde_plume wrote:
It is a fact that there are almost not circumstances when
it is necessary to use new and delete in C++ anymore,
Oh, I don't know about that. There's plenty of times when I need a countainer to maintain a reference to an object that isn't constructed on the stack.
nde_plume wrote:
However, Microsoft's secret plan to replace C++ with
C# is that they make these containers very hard to use
within the debugger.
Not really. STL has been a PITA to debug since the days when I was using Sun's STL. Drilling into a collection in STL is like bumbling around in a universe consisting of 3.2 dimensions. If anything, maybe Microsoft has made is easier, not harder, to debug.
Marc
My website
Traceract
Understanding Simple Data Binding
Diary Of A CEO - Preface
|
|
|
|
|
However, Microsoft's secret plan to replace C++ with
C# is that they make these containers very hard to use
within the debugger
You really think it isn't possible to present containers
in an easier way in the debugger? Heck, if you are using
a vector you can hack the debugger to display the contents
by typing this in the watch window:
my_vector._Myfirst,10
shows the first ten items in the vector in a fairly nice
way. There is no reason at all why the debugger can't do
that itself. It is much harder with tree structures like
maps and sets to view by hand in the debugger (though you
can walk throught it, so the data is certainly renderable)
it is just that MS didn't think it was very important.
|
|
|
|