VERY URGENT!!! Dynamic Arrays (Adding elements)
Ok, I have no idea how to do this, so I'm hoping someone here does. Would it be possible to add an element to an array after it has been declared and initialized with some number of elements? For example:
void main(){
int x[4];
x[0]=1;
x[1]=2;
x[2]=3;
x[3]=4;
?????????????
}
I have something like this, now how would I be able to add another element to this array? Please help, this is very urgent! Thanks.
There is some mistakes in the code.
There is some mistakes in the code.
I have edited and corrected it.
Do not use the code previously posted.
my explanation was for not using a class.
My code and explanation is for expanding a array without using class.
If you forget about tb_textbox and uses int instead by replacing every tb_textbox occurance with int. It will work. addtextbox() is a normal function, not a class function.
If you still want to use class, use the code below
Code:
#include<iostream.h>
#include<memory.h>
class tb_textbox
{
private:
static int size;
public:
int *x;
tb_textbox(void){x=new int[5]; return;};
void addtextbox(void);
~tb_textbox(void){delete [] x; return; };
};
void tb_textbox::addtextbox(void)
{
int *temp=new int[++size];
if (temp==0)
{
cerr<<"array allocation fails"<<endl;
return;
}
memcpy(temp,x,size*sizeof(int));
temp[size-1]=0;
if (x)
delete [] x;
x=temp;
return;
}
int tb_textbox::size=5; //you have to initialise static variables outside and like this.
int main()
{
tb_textbox tb;
tb.addtextbox();
tb.x[0]=2;
tb.addtextbox();
tb.x[1]=3;
cout<<tb.x[0]<<tb.x[1]<<endl;
return 0;
}
x cannot be 1, or else I kept getting illegal operation from windows so I set to 5. Took me some time to figure it out.
Now it is morning over Singapore.