Re: Shift elements of an array
On Sun, 06 Oct 2013 18:24:09 +0200, Rosario1903
<Rosario@invalid.invalid> wrote:
On Sun, 06 Oct 2013 18:16:59 +0200, Rosario1903
<Rosario@invalid.invalid> wrote:
friend ostream& operator<<(ostream& os, myarray& ma)
{u32 i;
if(ma.s!=0)
for(i=0; i<ma.s-1; ++i)
os<<ma.arr[i];
return os<<ma.arr[i];
^^^^^^^^^^^^^^^^^^^^^^^^^
this is one error...
it would be "return os<<ma.arr[ma.s-1]"
}
wrong too, i repost my solution
[it is possible i not had understood the problem too, excuse for the
time i make lost to you]
#include <iostream>
#include <stdlib.h>
using namespace std;
#define u32 unsigned
#define u8 unsigned char
class myarray{
public:
~myarray(){free(arr); arr=0; s=0;}
myarray(){arr=(u8*) malloc(15);
if(arr==0) exit(-1);
s=15;
}
myarray(u32 c)
{if(c>0xFFFF) exit(-1);
arr=(u8*)malloc(c);
if(arr==0) exit(-1);
s=c;
}
myarray(char* c)
{u32 v, i;
if(c==0)
{v=1;}
else {v=strlen(c)+1;}
arr=(u8*)malloc(v);
if(arr==0) exit(-1);
if(v==1) *arr=0;
else {for(i=0; i<v ; ++i)
{arr[i]=c[i];
if(c[i]==0) break;
}
for(; i<v;++i)
arr[i]=0;
}
s=v;
}
friend ostream& operator<<(ostream& os, myarray& ma)
{u32 i;
if(ma.s!=0)
{for(i=0; i<ma.s-1; ++i)
os<<ma.arr[i];
return os<<ma.arr[i];
}
else return os;
}
u32 shiftd(myarray& ma, u32 pos)
{u32 i, j;
if(s<ma.s)
{free(arr);
arr=(u8*)malloc(ma.s);
if(arr==0) exit(-1);
s=ma.s;
}
if(pos>=s)
{for(i=0;i<s; ++i) arr[i]=0;}
else {/* 0 1 2 3 4 5 6 */
/* | shiftd 3*/
j=pos;
for(i=0;j<s;++j,++i)
arr[i]=ma.arr[j];
for(;i<s;++i)
arr[i]=0;
}
return 1;
}
u32 s;
u8 *arr;
};
int main(void)
{myarray v("this and that"), ma;
cout<<"at start v=["<<v <<"]\n";
ma.shiftd(v, 3);
cout<<"at end ma=["<<ma<<"]\n";
return 0;
}