R
Ramprasad A Padmanabhan
Hi All,
I am a c/perl programmer trying my hand at C++.
In my code below I have an array class where I am trying to add two
arrays using "+" .
I am not sure why I get a '0' always for the first element of the result
My code ( slightly longish , I hope you would bear with a newbie )
--------------------------
using namespace std;
#include <iostream>
#define MAXARRAYSIZE 500
class MyArr {
public:
int *data,length;
MyArr(){
data = new int[0];
length = 0;
}
~MyArr(){
if(length) free(data);
}
void newFill(int *d,int l,bool freeD = true){
length = l;
if(freeD) free(data);
data = (int*) malloc(sizeof(int)*(length +2));
for(int i=0;i<length;i++) data = d;
}
void dispArr() {
for(int i=0;i<length;i++) cout << data <<"\t";
cout << "\n";
}
MyArr operator + ( const MyArr &r){
int a[length];
MyArr ret;
for(int i=0;i<length;i++) a= data + (r.data);
ret.newFill(a,length);
return(ret);
}
};
int main(){
MyArr a1,a2;
{
int d[]={0,1,2,3,4};
int d2[]={11,12,13,14,15};
a1.newFill(d,5);
a2.newFill(d2,5);
}
a1.dispArr();
a2.dispArr();
a2 = a1 + a2;
a2.dispArr();
return(0);
}
---------------------- END -------------------
Here is the output
0 1 2 3 4
11 12 13 14 15
0 13 15 17 19
------> I expect the first element of last row = 11
Thanks
Ram
I am a c/perl programmer trying my hand at C++.
In my code below I have an array class where I am trying to add two
arrays using "+" .
I am not sure why I get a '0' always for the first element of the result
My code ( slightly longish , I hope you would bear with a newbie )
--------------------------
using namespace std;
#include <iostream>
#define MAXARRAYSIZE 500
class MyArr {
public:
int *data,length;
MyArr(){
data = new int[0];
length = 0;
}
~MyArr(){
if(length) free(data);
}
void newFill(int *d,int l,bool freeD = true){
length = l;
if(freeD) free(data);
data = (int*) malloc(sizeof(int)*(length +2));
for(int i=0;i<length;i++) data = d;
}
void dispArr() {
for(int i=0;i<length;i++) cout << data <<"\t";
cout << "\n";
}
MyArr operator + ( const MyArr &r){
int a[length];
MyArr ret;
for(int i=0;i<length;i++) a= data + (r.data);
ret.newFill(a,length);
return(ret);
}
};
int main(){
MyArr a1,a2;
{
int d[]={0,1,2,3,4};
int d2[]={11,12,13,14,15};
a1.newFill(d,5);
a2.newFill(d2,5);
}
a1.dispArr();
a2.dispArr();
a2 = a1 + a2;
a2.dispArr();
return(0);
}
---------------------- END -------------------
Here is the output
0 1 2 3 4
11 12 13 14 15
0 13 15 17 19
------> I expect the first element of last row = 11
Thanks
Ram