Re: Shift elements of an array
Alf wrote:
That's because the C implicit conversion from literal
to non-const char* was deprecated in C++98 and REMOVED
in C++11 (the current standard).
one other error
there is no need of this ungly word "const"
AFAIK most compilers still support that conversion,
but they will probably not continue to support it for long.
So, use "char const*".
#include <iostream>
#include <cstdlib>
using namespace std;
#define u32 unsigned
#define u8 unsigned char
#define F for
#define R return
class myarray{
public:
~myarray(){free(arr);}
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 {F(i=0; i<v ; ++i)
{arr[i]=c[i];
if(c[i]==0) break;
}
F(; i<v;++i)
arr[i]=0;
}
s=v;
}
myarray& operator=(const myarray& r)
/* here i had to use the ugnly word "const" */
{u32 i;
if(s<r.s)
{free(arr);
arr=(u8*) malloc(r.s);
if(arr==0) exit(-1);
s=r.s;
}
F(i=0; i<r.s; ++i)
arr[i]=r.arr[i];
R *this;
}
friend ostream& operator<<(ostream& os, myarray& ma)
{u32 i;
if(ma.s!=0)
{F(i=0; i<ma.s-1; ++i)
os<<ma.arr[i];
R os<<ma.arr[i];
}
else R os;
}
void 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>=ma.s)
{F(i=0;i<s; ++i) arr[i]=0;}
else {/* 0 1 2 3 4 5 6 */
/* | shiftd 3*/
F(j=pos, i=0; j<ma.s; ++j,++i)
arr[i]=ma.arr[j];
F(;i<s;++i)
arr[i]=0;
}
}
u32 s;
u8 *arr;
};
myarray *bi[50]={0};
u32 index=0;
void fill_bi(myarray* a)
{if(index==49) exit(-1);
bi[index]=a;
++index;
}
void free_bi(void)
{myarray *a;
u32 i;
if(index!=0)
{F(i=index-1; ; --i)
{a=bi[i];
free(a->arr);
free(a);
bi[i]=0;
if(i==0) break;
}
}
index=0;
}
myarray& f(void)
{myarray a("1 2 3 4"), *b;
b=(myarray*)malloc(sizeof *b);
if(b==0) exit(-1);
b->arr=(u8*)malloc(15);
if(b->arr==0) exit(-1);
b->s=15;
fill_bi(b);
*b=a;
R *b;
}
int main(void)
{myarray v("this and that "), ma, b;
u32 i;
cout<<"at start v=["<<v <<"]\n";
ma.shiftd(v, 3);
cout<<"at end ma=["<<ma<<"]\n";
F(i=0;i<12;++i)
{ma.shiftd(ma, 1);
cout<<"at end ma=["<<ma<<"]\n";
}
b=v;
cout<<"b="<<b<<"\n";
b=f();
free_bi();
cout<<"b="<<b<<"\n";
R 0;
}