Is there a way to create dynamic arrays in C++?? If so.. how do i use them? A simple code example would be great.
Thanx, HeadExplodes.
Is there a way to create dynamic arrays in C++?? If so.. how do i use them? A simple code example would be great.
Thanx, HeadExplodes.
/* MSN and E-Mail - head_explodeshotmail.com */
If Bill Gates got a dollar for every time windows crahsed... oh... he does.
I always use MSVC++6.0
Jupp there is, with pointers. It could look something like this.
#include <iostream.h>
int main()
{
int *pInt = new int[10];
int *pIncre = pInt;
for (int i = 0; i < 10; i++)
{
*pIncre = 2*i;
pIncre++; // "jumps" to the next element
}
pIncre = pInt;
for (int i = 0; i < 10; i++)
{
cout << "Value pInt[" << i << "] is " << *pIncre << endl;
pIncre++;
}
delete [] pInt; //free memory(heap)
//dont use delete pInt because it only frees the
//fist element and you get a memory leak :-(
return 0;
}
This should work good (I havent test it yet). Please reply and tell how it went.
Jupp there is, with pointers. It could look something like this.
#include <iostream.h>
int main()
{
int *pInt = new int[10];
int *pIncre = pInt;
for (int i = 0; i < 10; i++)
{
*pIncre = 2*i;
pIncre++; // "jumps" to the next element
}
pIncre = pInt;
for (int i = 0; i < 10; i++)
{
cout << "Value pInt[" << i << "] is " << *pIncre << endl;
pIncre++;
}
delete [] pInt; //free memory(heap)
//dont use delete pInt because it only frees the
//fist element and you get a memory leak :-(
return 0;
}
This should work good (I havent test it yet). Please reply and tell how it went.
Or a simpler way to assign values to array in this case would be:
for (int i = 0; i < 10; i++) pInt[i] = i*2;
This does exactly same thing as:
for (int i = 0; i < 10; i++)
{
*pIncre = 2*i;
pIncre++;
}
Making error is human, but for messing things thoroughly it takes a computer
I totaly agree Kitten. Using vector is better in this case
(I just didnt want to mix vectors and pointers).
Okay, all of that stuff is hard coding, people. Arrays are naturally dynamic, because arrays are pointers. I highly suggest not using a pre-made vector class because you will not always have that vector class on you. Use your own knowledge.