Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Shift elements of an array

256 views
Skip to first unread message

axc...@gmail.com

unread,
Oct 4, 2013, 12:35:12 AM10/4/13
to
Hi all,

I have an array containing 15 elements. I want to shift the elements to the right and store the new array in another array, and keep the original array as is. Does anyone have any suggestions regarding this?

Thanks in advance

Paavo Helde

unread,
Oct 4, 2013, 12:47:53 AM10/4/13
to
axc...@gmail.com wrote in
news:f81f8d8d-4715-46c4...@googlegroups.com:
const int N=15;
double original[N] = {/*...*/};
double result[N];

int shift=3;
std::copy(original, original+N-shift, result+shift);
std::fill(result, result+shift, 0.0);

hth
Paavo


axc...@gmail.com

unread,
Oct 4, 2013, 1:53:56 AM10/4/13
to
Thanks for your help first of all. When I use this set of commands, I get the output:

0x7fff6f1e4ca0
0x7fff6f1e4ca0

What does this mean?

Thanks

Paavo Helde

unread,
Oct 4, 2013, 5:14:13 AM10/4/13
to
axc...@gmail.com wrote in
news:64390e01-c43c-44fa...@googlegroups.com:

> Thanks for your help first of all. When I use this set of commands, I
> get the output:
>
> 0x7fff6f1e4ca0
> 0x7fff6f1e4ca0

There are no commands for outputting anything in sight. See

http://www.parashift.com/c++-faq/posting-code.html

Juha Nieminen

unread,
Oct 4, 2013, 5:39:39 AM10/4/13
to
axc...@gmail.com wrote:
>> const int N=15;
>> double original[N] = {/*...*/};
>> double result[N];
>>
>> int shift=3;
>> std::copy(original, original+N-shift, result+shift);
>> std::fill(result, result+shift, 0.0);

> Thanks for your help first of all. When I use this set of commands, I get the output:

Btw, try to *understand* what the code is doing. Don't simply copy it
blindly. That won't help you at all.

--- news://freenews.netfront.net/ - complaints: ne...@netfront.net ---

Victor Bazarov

unread,
Oct 4, 2013, 8:38:30 AM10/4/13
to
And http://www.parashift.com/c++-faq/dont-ask-hw-probs.html while you're
at it.

V
--
I do not respond to top-posted replies, please don't ask

Vlad from Moscow

unread,
Oct 4, 2013, 10:17:06 AM10/4/13
to
Calls of the algorithms can be written in one line

std::copy( original, original + N - shift,
std::fill_n( result, shift, 0.0 ) );

provided that shift <= N

пятница, 4 октября 2013 г., 8:47:53 UTC+4 пользователь Paavo Helde написал:
Message has been deleted

Vlad from Moscow

unread,
Oct 4, 2013, 10:42:21 AM10/4/13
to
You are right. More correctly it would be to say "in one statement".:)

пятница, 4 октября 2013 г., 18:35:51 UTC+4 пользователь Stefan Ram написал:
> Vlad from Moscow writes:
>
> >Calls of the algorithms can be written in one line
>
> >std::copy( original, original + N - shift,
>
> > std::fill_n( result, shift, 0.0 ) );
>
>
>
> The above are /two/ lines.
>
>
>
> This, for example, is /one/ line:

Michael Groshart

unread,
Oct 4, 2013, 3:17:12 PM10/4/13
to
There is a standard library algorithm called std::rotate_copy that does exactly what you are asking.

Vlad from Moscow

unread,
Oct 4, 2013, 4:44:22 PM10/4/13
to
Rotating is not the same as shifting.

пятница, 4 октября 2013 г., 23:17:12 UTC+4 пользователь Michael Groshart написал:

Rosario1903

unread,
Oct 6, 2013, 6:14:40 AM10/6/13
to
On Fri, 4 Oct 2013 13:44:22 -0700 (PDT), Vlad from Moscow wrote:

>Rotating is not the same as shifting.
>

if you have in r[15] the rotate division of n bit of a[15]
for obtain the shift division it is enought fill the range of bit
15*sizeof(*a)*CHAR_BIT..(15*sizeof(*a)*CHAR_BIT-n)
with 0 bit

if it is shift mult
and ave in r[15] rotate mult
fill the range of r[15]
0..n with 0 bit

Rosario1903

unread,
Oct 6, 2013, 6:16:13 AM10/6/13
to
On Sun, 06 Oct 2013 12:14:40 +0200, Rosario1903
<Ros...@invalid.invalid> wrote:

>On Fri, 4 Oct 2013 13:44:22 -0700 (PDT), Vlad from Moscow wrote:
>
>>Rotating is not the same as shifting.
>>
>
>if you have in r[15] the rotate division of n bit of a[15]
>for obtain the shift division it is enought fill the range of bit
>15*sizeof(*a)*CHAR_BIT..(15*sizeof(*a)*CHAR_BIT-n)
>with 0 bit

pheraps better:
fill the range of bit
(15*sizeof(*a)*CHAR_BIT-1)..(15*sizeof(*a)*CHAR_BIT-n-1)

Vlad from Moscow

unread,
Oct 6, 2013, 10:12:46 AM10/6/13
to
I have understood nothing. What is the relation between the original task and your post?

воскресенье, 6 октября 2013 г., 14:14:40 UTC+4 пользователь Rosario1903 написал:

Rosario1903

unread,
Oct 6, 2013, 12:16:59 PM10/6/13
to
On Sun, 6 Oct 2013 07:12:46 -0700 (PDT), Vlad from Moscow wrote:

>I have understood nothing. What is the relation between the original task and your post?
>
>???????????, 6 ??????? 2013 ?., 14:14:40 UTC+4 ???????????? Rosario1903 ???????:
>> On Fri, 4 Oct 2013 13:44:22 -0700 (PDT), Vlad from Moscow wrote:
>>
>>
>>
>> >Rotating is not the same as shifting.
>>
>> >
>>
>>
>>
>> if you have in r[15] the rotate division of n bit of a[15]
>>
>> for obtain the shift division it is enought fill the range of bit
>>
>> 15*sizeof(*a)*CHAR_BIT..(15*sizeof(*a)*CHAR_BIT-n)
>>
>> with 0 bit
>>
>>
>>
>> if it is shift mult
>>
>> and ave in r[15] rotate mult
>>
>> fill the range of r[15]
>>
>> 0..n with 0 bit

i read wrong it seem to me the problem was shift one array of bit...
even if i'm not a C++ expert, this is my try in shift one array of
chars:

#include <iostream>
#include <stdlib.h>

using namespace std;
#define u32 unsigned
#define u8 unsigned char

class myarray{
public:
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];
}

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()
{myarray v("this and that"), ma;

cout<<"at start v=["<<v <<"]\n";
ma.shiftd(v, 3);
cout<<"at end ma=["<<ma<<"]\n";

return 0;
}
-----------------
at start v=[this and that ]
at end ma=[s and that ]

Rosario1903

unread,
Oct 6, 2013, 12:24:09 PM10/6/13
to
On Sun, 06 Oct 2013 18:16:59 +0200, Rosario1903
<Ros...@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]"

> }


Leigh Johnston

unread,
Oct 6, 2013, 12:28:16 PM10/6/13
to
#include <cstdlib>
and
uint8_t, uint32_t.

Also, "using namespace std;" is rather poor.

/Leigh

Rosario1903

unread,
Oct 6, 2013, 12:38:50 PM10/6/13
to
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)

Rosario1903

unread,
Oct 6, 2013, 12:59:06 PM10/6/13
to
On Sun, 06 Oct 2013 18:38:50 +0200, Rosario1903
<Ros...@invalid.invalid> wrote:

> 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)
^^^^^^^^^^^^^^^

here would be "for(i=0;j<ma.s;++j,++i)"

Paavo Helde

unread,
Oct 6, 2013, 12:59:07 PM10/6/13
to
Rosario1903 <Ros...@invalid.invalid> wrote in
news:3ju259t0iin89smlr...@4ax.com:

>
> #include <iostream>
> #include <stdlib.h>
>
> using namespace std;
> #define u32 unsigned
> #define u8 unsigned char
>
> class myarray{
> public:
> myarray(){arr=(u8*) malloc(15);
> if(arr==0) exit(-1);

Oh dear, in the first 9 non-empty lines of your code you managed to include
6 things which should be never used in a proper C++ program. I stopped
reading after that.

Even if this is some kind of elaborate joke to get the OP confused with his
homework, it is still not nice to post such code in a C++ newsgroup as also
other people might mistakenly believe this has something to do with C++.

Cheers
Paavo

Leigh Johnston

unread,
Oct 6, 2013, 1:02:26 PM10/6/13
to
I stopped reading after the fifth non-empty line. :)

/Leigh

Ian Collins

unread,
Oct 6, 2013, 2:48:19 PM10/6/13
to
Paavo Helde wrote:
> Rosario1903 <Ros...@invalid.invalid> wrote in
> news:3ju259t0iin89smlr...@4ax.com:
>
>>
>> #include <iostream>
>> #include <stdlib.h>
>>
>> using namespace std;
>> #define u32 unsigned
>> #define u8 unsigned char
>>
>> class myarray{
>> public:
>> myarray(){arr=(u8*) malloc(15);
>> if(arr==0) exit(-1);
>
> Oh dear, in the first 9 non-empty lines of your code you managed to include
> 6 things which should be never used in a proper C++ program. I stopped
> reading after that.

He (?) can usually be found posting such nonsense on c.l.c. I didn't
realise there had been an escape...

--
Ian Collins

Robert Wessel

unread,
Oct 6, 2013, 3:25:01 PM10/6/13
to
While I hate to contribute to this leg of the thread, you've got me
curious. I only see eight.

-the include of stdlib.h
-the using
-the two defines (and their pointless renaming of basic types)
-the raw pointer
-the C style cast
-the malloc
-the parameter to exit

What's the ninth? Perhaps the hard coded constant to malloc?

Robert Wessel

unread,
Oct 6, 2013, 3:27:19 PM10/6/13
to
Argh. Never mind. I misread your post as saying *nine* items (not
six). Of course I had to notice the error two minutes *after*
posting…

Paavo Helde

unread,
Oct 6, 2013, 4:53:05 PM10/6/13
to
Robert Wessel <robert...@yahoo.com> wrote in
news:9ae359l734h2o4js7...@4ax.com:
Yes, I counted 9 lines and 6 issues. I did not count stdlib.h and raw
pointer, these are sometimes useful in C++ as well (though probably not
in this example).

Cheers
Paavo


Paavo Helde

unread,
Oct 6, 2013, 5:11:25 PM10/6/13
to
Ian Collins <ian-...@hotmail.com> wrote in
news:bbdpjk...@mid.individual.net:

> He (?) can usually be found posting such nonsense on c.l.c. I didn't
> realise there had been an escape...

Oh, I see. Thankfully, my newsreader has a killfile feature.

Cheers
Paavo


Geoff

unread,
Oct 6, 2013, 5:39:51 PM10/6/13
to
On Sun, 06 Oct 2013 15:53:05 -0500, Paavo Helde <myfir...@osa.pri.ee>
wrote:

>Yes, I counted 9 lines and 6 issues. I did not count stdlib.h and raw
>pointer, these are sometimes useful in C++ as well (though probably not
>in this example).

Under what circumstances would including stdlib.h be preferable to
including cstdlib in a C++ program?

alf.p.s...@gmail.com

unread,
Oct 6, 2013, 5:54:00 PM10/6/13
to
On Sunday, October 6, 2013 11:39:51 PM UTC+2, Geoff wrote:
>
> Under what circumstances would including stdlib.h be preferable to
> including cstdlib in a C++ program?

When you're not bound by a coding guideline or work environment that forces you to do otherwise.

This was the case even with C++98 (and TC1 aka C++03), but with C++11 also the formal allows <cstdlib> & friends to pollute the global namespace.

In practical terms using the [.h] headers therefore means code that has a better chance of being portable (to other system or compiler or even just a new version of your compiler), plus it reduces needless verbosity.


Cheers & hth.,

- Alf

Leigh Johnston

unread,
Oct 6, 2013, 6:11:20 PM10/6/13
to
What needless verbosity? You're talking nonsense as usual Alf.

/Leigh

alf.p.s...@gmail.com

unread,
Oct 6, 2013, 6:11:46 PM10/6/13
to
On Friday, October 4, 2013 6:35:12 AM UTC+2, axc...@gmail.com wrote:
>
> I have an array containing 15 elements. I want to shift the elements to the right and store the new array in another array, and keep the original array as is. Does anyone have any suggestions regarding this?

auto const s1 = string( "123456789ABCDEF" );
auto const s2 = '0' + s1;

Leigh Johnston

unread,
Oct 6, 2013, 6:14:15 PM10/6/13
to
It is 'std::string' not 'string'. 'using namespace std;' is amateurish
at best Alf.

/Leigh

Vlad from Moscow

unread,
Oct 6, 2013, 6:35:54 PM10/6/13
to
std::string is not an array. So your code have nothing common with the assignment.

понедельник, 7 октября 2013 г., 2:11:46 UTC+4 пользователь alf.p.s...@gmail.com написал:

alf.p.s...@gmail.com

unread,
Oct 6, 2013, 7:07:33 PM10/6/13
to
On Monday, October 7, 2013 12:35:54 AM UTC+2, Vlad from Moscow wrote:
> std::string is not an array.

Non-expert readers will more readily understand that you're expressing a subjective OPINION about TERMINOLOGY, instead of a fact about the technical, when you include e.g. "IMHO means" and refer to e.g. "terminology" or "the word".

It's an interesting view though, because it's unconventional, has no advantage that I can see, and certainly is very impractical.

So, could you perhaps elaborate on what you think the defining characteristics of an "array" are -- and where you picked up this view?


> So your code have nothing common with the assignment.

I'm sorry, that's a fallacy.

Summing up, your posting consisted of (a) an impractical and unconventional subjective opinion about terminology, misleadingly expressed as an assertion about technical fact, and (2) a fallacy.

Leigh Johnston

unread,
Oct 6, 2013, 7:08:53 PM10/6/13
to
sausages.

Vlad from Moscow

unread,
Oct 6, 2013, 7:33:17 PM10/6/13
to
It would be musch better if you would edd bla...bla..bla.. and learn what is array in C/C++. ALso you should read the original post where is is clear enough said what type of data orhanization have to be used in the assignment.
Moreover your example has totally different symantic because it does not shift a sequane but add a new element at the its beginning. So the size of the resulting sequence differs from the original sequence.


понедельник, 7 октября 2013 г., 3:07:33 UTC+4 пользователь alf.p.s...@gmail.com написал:

alf.p.s...@gmail.com

unread,
Oct 6, 2013, 8:48:42 PM10/6/13
to
First, please don't top post, and please do read up on that now.

Some people here, e.g. Victor, will simply ignore you when you do that.

Others, such as I, take it as an indication of the total newbie or troll.

I'm giving you the benefit of assuming that you're a total newbie, even though I do vaguely recall a "vlad" troll here some years ago, and even though fantasy statements, fallacies, and incoherence (exhibited below, first quote) are very strongly indicative of trolling (sorry for mentioning this, but necessary).

So,

---

On Monday, October 7, 2013 1:33:17 AM UTC+2, Vlad from Moscow wrote:
> It would be musch better if you would edd bla...bla..bla..

Sorry, that's incoherent, it reads like gobbledegook to me.


> and learn what is array in C/C++.

I'm sorry, but there is no such language as "C/C++".

Notwithstanding the misleading title of a Microsoft book.

In particular, much modern C code is not valid as C++ code, some C code does compile as C++ but means something different in C++, and some best practices (e.g. whether to cast the result of malloc, if one uses malloc) are diametrically opposite, or differ, between the languages.

It's therefore best to not start out by conflating the languages.

Especially for a newbie.


> ALso you should read the original post where is is clear enough said what
> type of data orhanization have to be used in the assignment.

It's true that the type of data organization used by the OP is clear, namely an array.

There is no conflict between that and my simple suggestion of using std::string and its concatenation operation.

The answer may not, however, apply to all possible choices of item data. But the OP did not ask for that. The OP asked for "any suggestions" and got one, which happens to be much simpler than the answers so far, including yours.

Since I must assume that you are a newbie, as indicated by your top-posting, and as indicated by your ignorance of what arrays are, and more,

* the OP is most likely dealing with strings or data easily represented as strings,

* std::string provides constant time indexing, so it's a logical array, and it has a guaranteed contiguous buffer, so it's also an array by memory layout criterions (however misguided it would be to apply such criterions here), and

* in the cases where the provided solution fits it's very simple and clear and does the job, contrary to your opinion that it's irrelevant.


> Moreover your example has totally different symantic because it does not
> shift a sequane but add a new element at the its beginning.

Shifting to the right always adds a new element to the beginning.

If you don't introduce a new element then you're moving around the rightmost element, in which case it's called "rotating" rather than "shifting".


> So the size of the resulting sequence differs from the original sequence.

Yes, the OP neglected to state anything about the size, so I did not add code to trim down the size.

If such code were added (it's trivial and very short, E.G. a call to .resize()) then one could equally well argue that it should not be there, depending on what one thinks is most likely the unstated requirement. For example, in arbitrary precision arithmetic, "bignum" arithmetic, shifting (to the left) does extend the sequence. The OP has not clarified what he/she wants.

I do not now and have never viewed comp.lang.c++ as a question-and-answer forum: while comp.lang.c++ does not have a charter, it's traditionally a discussion and learning forum, which is a very different kind of beast than Q&A. Newbie Q&A is best done in alt.comp.lang.learn.c-c++ or other groups dedicated to that sort of thing. Which is not to say that this group is not inclusive -- it is! -- but what kinds of answers can be considered appropriate or inappropriate or incomplete, is very different.

Anyway, in the absence of a specification it's best to not needlessly assume, and not needlessly add complicating details -- the OP can do that.


Cheers, and hope this helps! :-);

- Alf

Vlad from Moscow

unread,
Oct 7, 2013, 12:19:58 AM10/7/13
to
It seems you are indeed a troll. As I said your code !). has nothing common with the original assignment 2) has a totally different semantic. So you only confuse others and flood.

And it is your who should obviously be ignored.

понедельник, 7 октября 2013 г., 4:48:42 UTC+4 пользователь alf.p.s...@gmail.com написал:

Rosario1903

unread,
Oct 7, 2013, 2:03:31 AM10/7/13
to
On Sun, 06 Oct 2013 18:59:06 +0200, Rosario1903 wrote:
the last version for this exercise.

#include <iostream>
#include <cstdlib>

using namespace std;
#define u32 unsigned
#define u8 unsigned char

class myarray{
public:
~myarray(){free(arr);}
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>=ma.s)
{for(i=0;i<s; ++i) arr[i]=0;}
else {/* 0 1 2 3 4 5 6 */
/* | shiftd 3*/
for(j=pos, i=0; j<ma.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;
u32 i;

cout<<"at start v=["<<v <<"]\n";
ma.shiftd(v, 3);
cout<<"at end ma=["<<ma<<"]\n";

for(i=0;i<12;++i)
{ma.shiftd(ma, 1);
cout<<"at end ma=["<<ma<<"]\n";
}

return 0;
}

---------------
at start v=[this and that ]
at end ma=[s and that ]
at end ma=[ and that ]
at end ma=[and that ]
at end ma=[nd that ]
at end ma=[d that ]
at end ma=[ that ]
at end ma=[that ]
at end ma=[hat ]
at end ma=[at ]
at end ma=[t ]
at end ma=[ ]
at end ma=[ ]
at end ma=[ ]

alf.p.s...@gmail.com

unread,
Oct 7, 2013, 2:05:25 AM10/7/13
to
On Monday, October 7, 2013 6:19:58 AM UTC+2, Vlad from Moscow wrote:
> It seems you are indeed a troll. As I said your code !). has nothing common with the original assignment 2) has a totally different semantic. So you only confuse others and flood.

I'm sorry, that's quite lunatic..., except that


> And it is your who should obviously be ignored.

... you guessed that I would plink you. Good thinking.

Plink.


- Alf

Rosario1903

unread,
Oct 7, 2013, 2:40:41 AM10/7/13
to
On Sun, 06 Oct 2013 15:53:05 -0500, Paavo Helde
<myfir...@osa.pri.ee> wrote:

>Robert Wessel <robert...@yahoo.com> wrote in
>news:9ae359l734h2o4js7...@4ax.com:
>
>> On Sun, 06 Oct 2013 14:25:01 -0500, Robert Wessel
>> <robert...@yahoo.com> wrote:
>>
>>>On Sun, 06 Oct 2013 11:59:07 -0500, Paavo Helde
>>><myfir...@osa.pri.ee> wrote:
>>>
>>>>Rosario1903 <Ros...@invalid.invalid> wrote in
>>>>news:3ju259t0iin89smlr...@4ax.com:
>>>>
>>>>>
>>>>> #include <iostream>
>>>>> #include <stdlib.h>
>>>>>
>>>>> using namespace std;
>>>>> #define u32 unsigned
>>>>> #define u8 unsigned char
>>>>>
>>>>> class myarray{
>>>>> public:
>>>>> myarray(){arr=(u8*) malloc(15);
>>>>> if(arr==0) exit(-1);

see if i know what he think above it is wrong

1)"using namespace std;" should be not used
[so i woudl use always std::etc]
2) #define u32 wrong for he
3) #define u8 wrong for he
[so i wuold write "unsigned int" all the code lenght; that for
write just one it take one day...]
4) using "public:" as class data [there would be private for him]
5) the using of malloc() for memory usage
6) the use of exit instead of use exception

but i'm not agree expecially point 5... using malloc() is always
easier [to debug too] than use new().

alf.p.s...@gmail.com

unread,
Oct 7, 2013, 3:07:52 AM10/7/13
to
On Monday, October 7, 2013 8:03:31 AM UTC+2, Rosario1903 wrote:
> On Sun, 06 Oct 2013 18:59:06 +0200, Rosario1903 wrote:
>
> the last version for this exercise.

Usually when people post code in comp.lang.c++, at least as of old they have expected a review. Else why post it? So, review.

First, I illustrate the main point, that the code is needlessly complicated and verbose. The complexity also means that the code's brittle (will easily break in maintainance). Here's shorter and simpler code that produces essentially the same output as your program ("essentially": the lead text has been clarified):

[code]
#include <iostream>
#include <string>
using namespace std;

void shift_left( string& s, int n = 1 )
{ s = s.erase( 0, n ) + string( n, ' ' ); }

auto main() -> int
{
string s = "this and that";
cout << "at start: '" << s << "'\n";

shift_left( s, 3 );
cout << "after shift 3: '" << s << "'\n";

for( int i = 1; i <= 12; ++i )
{
shift_left( s );
cout << "after shift 1: '" << s << "'\n";
}
}
[/code]



> #include <iostream>
> #include <cstdlib>
>
> using namespace std;
>
> #define u32 unsigned
> #define u8 unsigned char

Macros do not respect scopes, so they can easily lead to unintended text substitutions.

Therefore, to the degree possible, avoid macros.

And where you do use macros, adopt the (now) common convention of ALL UPPERCASE names for macros, which reduces the probability of unintended text substitution.

The u32 definition does not necessarily define a 32-bit type name.

If you really want a 32-bit thing, use the <stdint.h> header.


> class myarray{
>
> public:
>
> ~myarray(){free(arr);}

Instead of C level malloc and free, use C++ new and delete.

And instead of C++ new and delete, preferentially use standard library containers such as std::vector, which deal automatically with deallocation.

One reason is that otherwise you will likely run afoul of the "rule of three" (or in C++11 sometimes now referred to as the "rule of five").

Essentially that means getting Undefined Behavior.


> myarray(){arr=(u8*) malloc(15);
>
> if(arr==0) exit(-1);
>
> s=15;
>
> }

Here with a std::string or std::vector you could just say

myarray(): arr( 15, ' ' ) {}

However the effect is /slightly/ different.

Your code produces an array of 15 items each of INDETERMINATE VALUE, while the suggested replacement produces an array of 15 items each with the space character code (which in ASCII is 32).


> myarray(u32 c)

Since this generalizes the default constructor, you could code both up as the same constructor with a defaulted argument, like this:

myarray( u32 c = 15 )

However, in order to avoid problems with implicit promotions, which can cause unintended wrap-around with unsigned types, preferentially use a signed type, and also, to enhance readability preferentially use descriptive names:

myarray( int size = 15 )

> {if(c>0xFFFF) exit(-1);

Here better use an "assert", from <assert.h>.

> arr=(u8*)malloc(c);

As before, better use C++ new and delete, and wrt. those operators, preferentially instead use standard library containers.


> if(arr==0) exit(-1);

As before, use "assert".

>
> s=c;
> }

Regarding the member initializations, in some cases one HAS TO use memory initializers, the ":" notation. And that's generally most efficient also. So as a general rule, prefer ":" to assignments in a constructor body.


> myarray(char* c)

Here the "char*" prevents the code from compiling with a conforming C++ compiler.

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).

AFAIK most compilers still support that conversion, but they will probably not continue to support it for long.

So, use "char const*".


> {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;
> }

Generally the specific indentation rules don't matter as long as they're applied consistently.

However, the above indentation rules, which result in different indent sizes, is not very clear.

To some degree it defeats the purpose of indentation.


> friend ostream& operator<<(ostream& os, myarray& ma)

The lack of "const" prevents passing a "const" myarray to <<.

Do like this:

friend ostream& operator<<( ostream&, myarray const& ma )


>
> {u32 i;
> if(ma.s!=0)

Better establish a guaranteed s != 0 in every constructor.

And don't change that property in any member function.

That's then called a CLASS INVARIANT, and can then simply be assumed everywhere without further checking.


> {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)

Ken Thompson (I think it was) was once asked what he'd do different if he were to design Unix again.

Answer: "I'd spell creat with an E".

Just avoid silly shortenings like "shiftd". Spell it out, like "shifted".

There is another possible improvement here, because a member function that updates this object's value with a copy of a modification of another object's value, is quite unusual and counter-intuitive.

Instead just provide a pure modifier member function, or a pure value producer member function.


> {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)
> {for(i=0;i<s; ++i) arr[i]=0;}
> else {/* 0 1 2 3 4 5 6 */
> /* | shiftd 3*/
> for(j=pos, i=0; j<ma.s; ++j,++i)
> arr[i]=ma.arr[j];
> for(;i<s;++i)
> arr[i]=0;
> }
>
> return 1;

Always returning the same numeric value indicates that a numeric function result is not really meaningful.

Perhaps this member function should have been declared "void".


> }
>
> u32 s;
> u8 *arr;

Generally, when a class has at least one constructor, then it's a good idea to make data members "private" or at least "protected", so as to avoid other code inadvertently changing those data members directly and e.g. invalidating the class invariant.

> };
>
> int main(void)

The "void" here is good practice in C, where it specifies that this function has no arguments, as opposed to accepting any number of arguments.

In C++ it's accepted just for C compatibility, but has no purpose: in C++ the signature "int main()" already says that there are no arguments.

So, it's a C-ism, which is best avoided -- because the two languages are fundamentally different, and should best not be conflated with each other.

> {myarray v("this and that "), ma;
>
> u32 i;

In C++ better declare variables as near their first use as possible.

In this case, write e.g. "for( u32 i = 0, ...".

However, as mentioned, it's even better to write just "for( int i = 0, ...".

> cout<<"at start v=["<<v <<"]\n";
> ma.shiftd(v, 3);
> cout<<"at end ma=["<<ma<<"]\n";
>
> for(i=0;i<12;++i)
> {ma.shiftd(ma, 1);
> cout<<"at end ma=["<<ma<<"]\n";
> }

> return 0;

In both C++ and C it's now unnecessary to return 0 from main, as that's the default.

It has always been the default in C++.

However, many programmers still prefer to indicate the "main" return value explicitly. For that purpose it can be a good idea to use the symbolic values EXIT_SUCCESS and EXIT_FAILURE from <stdlib.h>. In this case, EXIT_SUCCESS, which is what 0 means in this context.

> }

As a general comment, since myarray does not take charge of copying -- it does not declare any copy constructor or assignment operator -- any use of it that inadvertently invokes copying, will in general cause the same memory to be deallocated twice (via the free call in the destructor), invoking Undefined Behavior, such as e.g. a crash... :-(

In C++03 this is known as the "rule of three":

namely, if you need a destructor, a copy constructor or an assignment operator, then you most probably need ALL THREE.


> ---------------
>
> at start v=[this and that ]
> at end ma=[s and that ]
> at end ma=[ and that ]
> at end ma=[and that ]
> at end ma=[nd that ]
> at end ma=[d that ]
> at end ma=[ that ]
> at end ma=[that ]
> at end ma=[hat ]
> at end ma=[at ]
> at end ma=[t ]
> at end ma=[ ]
> at end ma=[ ]
> at end ma=[ ]

Again, note that the much shorter and simpler code shown at the start, produces essentially the same output.

Simpler and shorter = safer.

Rosario1903

unread,
Oct 7, 2013, 8:37:37 AM10/7/13
to
On Mon, 7 Oct 2013 00:07:52 -0700 (PDT), alf wrote:

>On Monday, October 7, 2013 8:03:31 AM UTC+2, Rosario1903 wrote:
>> On Sun, 06 Oct 2013 18:59:06 +0200, Rosario1903 wrote:
>>
>> the last version for this exercise.
>
>Usually when people post code in comp.lang.c++, at least as of old they
>have expected a review. Else why post it? So, review.
>
>First, I illustrate the main point, that the code is needlessly
>complicated and verbose. The complexity also means that the code's
>brittle (will easily break in maintainance). Here's shorter and
>simpler code that produces essentially the same output as your
>program ("essentially": the lead text has been clarified):
>
>[code]
>#include <iostream>
>#include <string>
>using namespace std;
>
>void shift_left( string& s, int n = 1 )
>{ s = s.erase( 0, n ) + string( n, ' ' ); }

it is required from OP the result is in one other array
result!=argument
than it is required the array is 15 elements

>As a general comment, since myarray does not take charge
>of copying -- it does not declare any copy constructor
>or assignment operator -- any use of it that
>inadvertently invokes copying, will in general cause
>the same memory to be deallocated twice (via the free
>call in the destructor), invoking Undefined Behavior,
>such as e.g. a crash... :-(

if the compiler use constructor i wrote, and distructor i wrote there
are no problem
can you modify the code i wrote so i can see that? [a seg fault]

>In C++03 this is known as the "rule of three":
>
>namely, if you need a destructor, a copy constructor or an assignment
>operator, then you most probably need ALL THREE.

possibly

>> ---------------
>>
>> at start v=[this and that ]
>> at end ma=[s and that ]
>> at end ma=[ and that ]
>> at end ma=[and that ]
>> at end ma=[nd that ]
>> at end ma=[d that ]
>> at end ma=[ that ]
>> at end ma=[that ]
>> at end ma=[hat ]
>> at end ma=[at ]
>> at end ma=[t ]
>> at end ma=[ ]
>> at end ma=[ ]
>> at end ma=[ ]
>
>Again, note that the much shorter and simpler code shown at the start, produces essentially the same output.
>
>Simpler and shorter = safer.
>
>
>Cheers & hth.,
>
>- Alf

you have confidence in call functions, i instead like loops...

Rosario1903

unread,
Oct 7, 2013, 8:57:18 AM10/7/13
to
On Mon, 07 Oct 2013 14:37:37 +0200, Rosario1903
<Ros...@invalid.invalid> wrote:

>On Mon, 7 Oct 2013 00:07:52 -0700 (PDT), alf wrote:
>
>>On Monday, October 7, 2013 8:03:31 AM UTC+2, Rosario1903 wrote:
>>> On Sun, 06 Oct 2013 18:59:06 +0200, Rosario1903 wrote:
>>As a general comment, since myarray does not take charge
>>of copying -- it does not declare any copy constructor
>>or assignment operator -- any use of it that
>>inadvertently invokes copying, will in general cause
>>the same memory to be deallocated twice (via the free
>>call in the destructor), invoking Undefined Behavior,
>>such as e.g. a crash... :-(
>
>if the compiler use constructor i wrote, and distructor i wrote there
>are no problem
>can you modify the code i wrote so i can see that? [a seg fault]

yes i find it... is is enougt add the function
myarray f(void)
{myarray a("1 2 3 4");
return a;
}

and put in some place in main
mystring ma;
ma=f()
cout <<"ma="<<ma<<"\n";

for see wrong ouput and seg fault...
but i not use that code in the example...
not use "operator="

Juha Nieminen

unread,
Oct 7, 2013, 9:18:47 AM10/7/13
to
Vlad from Moscow <vlad....@mail.ru> wrote:
> std::string is not an array.

What exactly makes it not an array?

--- news://freenews.netfront.net/ - complaints: ne...@netfront.net ---

Öö Tiib

unread,
Oct 7, 2013, 1:31:09 PM10/7/13
to
On Monday, 7 October 2013 16:18:47 UTC+3, Juha Nieminen wrote:
> Vlad from Moscow <vlad....@mail.ru> wrote:
> > std::string is not an array.
>
> What exactly makes it not an array?

* "Array" in computer science is collection of elements where elements
can be indexed with numeric indexes. std::string is array in computer
science.

* In C++ we usually call raw array as "array". Other arrays we usually
call by specific names (like "vector", "valarray" or "string literal").
std::string is rarely referred as "array" in C++.

* OP is likely novice student so "correct" answer for her is whatever
her teacher expects. If Vlad from Moscow is her teacher then std::string
is not an array, otherwise it might be.

Vlad from Moscow

unread,
Oct 7, 2013, 1:55:27 PM10/7/13
to
array is a derived type. It is not user-defined type. Arrays have no methods and they can not increase or decrease in size. So for example the semantic of "deleting" or "shifting" elements in an array is different than in a user-defined type such as for example std::vector. The size of an array have to be known in compilation time.

Vlad from Moscow

unread,
Oct 7, 2013, 2:00:26 PM10/7/13
to
You are wrong. You omit the important characteristic of arrays that they have fixed sizes. They are unable to add new elements orto delete existent elements. It is this their characteristic that is the reason that other containers as for example std::vector are required.

понедельник, 7 октября 2013 г., 21:31:09 UTC+4 пользователь Öö Tiib написал:
> On Monday, 7 October 2013 16:18:47 UTC+3, Juha Nieminen wrote:
>

Paavo Helde

unread,
Oct 7, 2013, 2:05:27 PM10/7/13
to
Rosario1903 <Ros...@invalid.invalid> wrote in
news:1vk459tm9piuplmgc...@4ax.com:
>
> but i'm not agree expecially point 5... using malloc() is always
> easier [to debug too] than use new().

Nobody is suggesting to use new here. Instead, use std::vector or
std::array for holding arrays.

Vlad from Moscow

unread,
Oct 7, 2013, 2:07:47 PM10/7/13
to
And where did you see that his (or her) teacher spoke about std:;string?!!! I think that he is competent enough in contrast to this troll alf.p.s...@gmail.com and is capable to call things with their names.


- показать цитируемый текст -

понедельник, 7 октября 2013 г., 21:31:09 UTC+4 пользователь Öö Tiib написал:
> On Monday, 7 October 2013 16:18:47 UTC+3, Juha Nieminen wrote:
>

Vlad from Moscow

unread,
Oct 7, 2013, 2:51:38 PM10/7/13
to
Your code is ignorant.

Remember if you use containers you should use types defined in them. So at least the function should be declared as

void shift_left( std::string& s, std::string::size_type n = 1 );

Moreover in this statement

s = s.erase( 0, n ) + string( n, ' ' );

you allocate a new string. It is simply a stupidy.

And the return type void in this case is the worst return type.


понедельник, 7 октября 2013 г., 11:07:52 UTC+4 пользователь alf.p.s...@gmail.com написал:

Ian Collins

unread,
Oct 7, 2013, 3:03:05 PM10/7/13
to
Vlad from Moscow wrote:
> Your code is ignorant.

Please stop top-posting (it's ignorant behaviour) and and quoting all
the added crap that shite google interface adds.

--
Ian Collins

Rosario1903

unread,
Oct 7, 2013, 3:29:51 PM10/7/13
to
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;
}


Vlad from Moscow

unread,
Oct 7, 2013, 3:31:29 PM10/7/13
to
It is an example of how code shall not be written.

понедельник, 7 октября 2013 г., 11:07:52 UTC+4 пользователь alf.p.s...@gmail.com написал:

Rosario1903

unread,
Oct 7, 2013, 3:54:03 PM10/7/13
to
On Mon, 07 Oct 2013 14:37:37 +0200, Rosario1903
<Ros...@invalid.invalid> wrote:

>it is required from OP the result is in one other array
>result!=argument

>than it is required the array is 15 elements

even if it not seems, all myarray object would have size==15 there...

Vlad from Moscow

unread,
Oct 7, 2013, 4:23:40 PM10/7/13
to
It will be funny to count how many times the memory is deallocated and allocated anew and how many times constructors including the move assignment operator are called in this stupid statement.

{ s = s.erase( 0, n ) + string( n, ' ' ); }


понедельник, 7 октября 2013 г., 11:07:52 UTC+4 пользователь alf.p.s...@gmail.com написал:

alf.p.s...@gmail.com

unread,
Oct 7, 2013, 4:39:21 PM10/7/13
to
On Monday, October 7, 2013 9:29:51 PM UTC+2, Rosario1903 wrote:
> 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

Well you haven't got to a FIRST error yet.

But you think that you have.

This group used to be frequented by the language creator (Bjarne), by the committee secretaries who penned the standard (first Andrew, then Pete), and by lots of committee members, compiler writers (including Greg Comeau and Daveed) and so on.

About the only authoritative people I see here now are some old-time clc++-ers like Ian Collins and "Tib" (I can never recall the name!), plus us old clc++m moderators (James, Victor and myself). That is, to the degree that having participated for a long time on Usenet confers any authority (except that James is also a committee member, I think). So it's gone downhill with the influx of novices and trolls, called "November" in Usenet jargon.

This means that you would do well by generally IGNORING or at least CHECKING statements here that are not rooted in simple verifiable fact, or clear logic.


> there is no need of this ungly word "const"

In the C++11 standard the easiest way to confirm that it indeed is needed is the Annex C (about C compatibility) discussion of §2.14.5 (string literals), which includes this example:

char* p = "abc"; // valid in C, invalid in C++

But if someone coughs that up as a reference, then don't just blindly believe it. For EXAMPLES in the standard are not "normative", which means that they can be wrong. Indeed, a whole bunch of examples in C++98 were incorrect (it's mostly corrected now in C++11).

The standardeese that that now forbids that implicit conversion is difficult to find, because it was done by simply REMOVING the C++03 text that allowed it,

C++03 §4.2/2
"A string literal (2.13.4) that is not a wide string literal can be
converted to an rvalue of type “pointer to char”;"

I.e., it's a case of finding the absence of text ;-); in C++11 there is no such.

Here's an example:

[code]
#include <iostream>
using namespace std;

// Intentionally does not compile with CONFORMING compiler:
void say( char* s )
{
cout << s << endl;
}

auto main() -> int
{
say( "Uh oh..." );
}
[/code]

Compiling with a MinGW Windows variant of g++ (the GNU C++ compiler) in C++11-confoming mode -- I'm not quite sure what options I've used, because it's all in the configuration:

[example]
[D:\dev\test]
> g++ foo.cpp
foo.cpp: In function 'int main()':
foo.cpp:12:21: error: deprecated conversion from string constant to 'char*' [-Werror=write-strings]
cc1plus.exe: some warnings being treated as errors

[D:\dev\test]
> _
[/example]

alf.p.s...@gmail.com

unread,
Oct 7, 2013, 4:48:18 PM10/7/13
to
On Monday, October 7, 2013 10:39:21 PM UTC+2, alf.p.s...@gmail.com wrote:
> influx of novices and trolls, called "November" in Usenet jargon.

Oh sorry I meant "September".

I was thinking about something else.

But as a relevant side note, I believe the free NNTP server called "Eternal September" is still up and running, and using that, e.g. via Mozilla Thunderbird, I will not have to deal with this Google Groups interface that double-spaces text, drops references, sabotages signature markers etc (I can't really believe that it's just incompetence!).


Cheers, & sorry 'bout that,

- Alf

red floyd

unread,
Oct 7, 2013, 7:25:48 PM10/7/13
to
eternal-september.org *is* still up and running, Alf. That's what I'm
using to post right now.



alf.p.s...@gmail.com

unread,
Oct 7, 2013, 7:37:31 PM10/7/13
to
On Tuesday, October 8, 2013 1:25:48 AM UTC+2, red floyd wrote:
>
> eternal-september.org *is* still up and running, Alf. That's what I'm
>
> using to post right now.

Thanks!

Will get to it (register anew) today or tomorrow I think.

Nice to see yet another known face. :-)


Cheers,

- Alf

Paavo Helde

unread,
Oct 8, 2013, 1:10:24 AM10/8/13
to
Vlad from Moscow <vlad....@mail.ru> wrote in
news:8b941d5e-13f9-4226...@googlegroups.com:

> It will be funny to count how many times the memory is deallocated and
> allocated anew and how many times constructors including the move
> assignment operator are called in this stupid statement.
>
> { s = s.erase( 0, n ) + string( n, ' ' ); }

This only counts if there is any concern about performance. If this
operation is executed e.g. only in some silly GUI event handler after some
user action, then who cares? This clearly expresses the intent and is more
concise (one statement only) than alternatives.


Rosario1903

unread,
Oct 8, 2013, 1:10:31 AM10/8/13
to
On Mon, 7 Oct 2013 13:39:21 -0700 (PDT), alf.p.steinbach wrote:

>On Monday, October 7, 2013 9:29:51 PM UTC+2, Rosario1903 wrote:
>> 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
>
>Well you haven't got to a FIRST error yet.
>
>But you think that you have.
>
>This group used to be frequented by the language creator (Bjarne),
>by the committee secretaries who penned the standard (first
>Andrew, then Pete), and by lots of committee members, compiler
>writers (including Greg Comeau and Daveed) and so on.
>
>About the only authoritative people I see here now are some
>old-time clc++-ers like Ian Collins

yes Ian Collins... where is his example for resolve OP problem?

>and "Tib" (I can never
>recall the name!), plus us old clc++m moderators (James,
>Victor and myself). That is, to the degree that having
>participated for a long time on Usenet confers any
>authority (except that James is also a committee member,
>I think). So it's gone downhill with the influx of novices and
>trolls, called "November" in Usenet jargon.

i'm not too much smart, it is so that i like simple languages, that
show well what one do, and are scalable in complexity

>This means that you would do well by generally IGNORING or at
>least CHECKING statements here that are not rooted in
>simple verifiable fact, or clear logic.

free of ignoring; i not have too much to show. i not wrote big
programs

>> there is no need of this ungly word "const"
>
>In the C++11 standard the easiest way to confirm that it
>indeed is needed is the Annex C (about C compatibility) discussion
>of §2.14.5 (string literals), which includes this example:
>
> char* p = "abc"; // valid in C, invalid in C++

why i would not write in the mem where there are "abc"?

>But if someone coughs that up as a reference, then don't just
>blindly believe it. For EXAMPLES in the standard are not "normative",
>which means that they can be wrong. Indeed, a whole bunch of
>examples in C++98 were incorrect (it's mostly corrected now in C++11).

why add one word "const", that has the only purpose of add complexity?
string costant is not a string constant
it is a char array where one can write
and we resolve the problem

Rosario1903

unread,
Oct 8, 2013, 1:12:19 AM10/8/13
to
On Mon, 7 Oct 2013 13:23:40 -0700 (PDT), Vlad from Moscow
<vlad....@mail.ru> wrote:

>It will be funny to count how many times the memory is
>deallocated and allocated anew and how many times constructors
>including the move assignment operator are called in
>this stupid statement.
>
>{ s = s.erase( 0, n ) + string( n, ' ' ); }

why you not write some code and post it?

Paavo Helde

unread,
Oct 8, 2013, 1:21:51 AM10/8/13
to
Rosario1903 <Ros...@invalid.invalid> wrote in
news:4v3759h2is5pv5mcr...@4ax.com:

> why add one word "const", that has the only purpose of add complexity?

You have got it backwards. A const variable or interface is less complex to
use, not more. It is only by an historic accident that the default mode is
non-const and so using const looks like adding complexity textually.

In a new C++-style language designed from scratch const would be the
default and there would be a 'mutable' keyword instead.

cheers
Paavo

Tobias Müller

unread,
Oct 8, 2013, 1:55:07 AM10/8/13
to
Rosario1903 <Ros...@invalid.invalid> wrote:
> On Mon, 7 Oct 2013 13:39:21 -0700 (PDT), alf.p.steinbach wrote:
>
>> On Monday, October 7, 2013 9:29:51 PM UTC+2, Rosario1903 wrote:
>>> there is no need of this ungly word "const"
>>
>> In the C++11 standard the easiest way to confirm that it
>> indeed is needed is the Annex C (about C compatibility) discussion
>> of §2.14.5 (string literals), which includes this example:
>>
>> char* p = "abc"; // valid in C, invalid in C++
>
> why i would not write in the mem where there are "abc"?

1. Because the standard says so

2. Many compilers do string pooling: All string literals with the same
value may point to the same memory. If you change one of them, you change
all.

3. Because string literals are "const", the compiler is allowed to put them
into memory that is marked as read-only. If you try to manipulate, your
program will crash.

>> But if someone coughs that up as a reference, then don't just
>> blindly believe it. For EXAMPLES in the standard are not "normative",
>> which means that they can be wrong. Indeed, a whole bunch of
>> examples in C++98 were incorrect (it's mostly corrected now in C++11).
>
> why add one word "const", that has the only purpose of add complexity?

While "const" adds complexity, it also adds safety, performance and
correctness.

- Safety: "const" helps to propagate the information which memory is read
only and not allowed to be changed.

- Correctness: If a function takes an argument per const& or const*, it
tells you "I won't modify your variable", which is useful documentation. It
prevents accidental data modification.

- Performance: The compiler can use more optimizations on constant data,
like string pooling mentioned before.
We're not discussing about changing the language, but about writing correct
code in C++.

If you think that C++ is too complex, then use another language. For
example an untyped or weakly type language, that has less restrictions. But
be aware, less restrictions means also less guarantees.

Tobi

Vlad from Moscow

unread,
Oct 8, 2013, 2:38:10 AM10/8/13
to
It is simply is very silly and bad code. The memory allocated and deallocated at least two times.And this code demonstrates only one intention that the author is unable to write programs.

In this simple function that contains only two lines in the body the author made three serious errors.

First the function has undefined behaviour because its second parameter is defined as int. So any value of type std::string::size_type that can not be fit into int will result in undefined behaviour of the function.

Second, the interface of the function is inconsistent with the interface of std::basic_string. See the description of std::basic_string in the C++ Standard.

Third, this function allocates and deallocates memory at least two times. As a result 1) the memory will be fragmented; 2) it is possible that allocating of memory will fail for large strings.
And it is a stupidy to allocate a new memory then the original string has enough memory that to do the operation "in place".

It needs to have a great talant that to write such a dull code!:) If a programmer is unable to write even such simple functions with only two lines of code then what to say about his capabilities to write code in whole?!!! :)


вторник, 8 октября 2013 г., 9:10:24 UTC+4 пользователь Paavo Helde написал:
> Vlad from Moscow wrote in

Vlad from Moscow

unread,
Oct 8, 2013, 2:49:47 AM10/8/13
to
No problem!

The correct definition of the function looks the following way

std::string & shift_left( std::string &s, std::string::size_type n = 1 )
{
return ( s.erase( 0, n ).append( n, ' ' ) );
}

Or if you do not like when two operations are written in one line you can rewrite it as

std::string & shift_left( std::string &s, std::string::size_type n = 1 )
{
s.erase( 0, n );

return ( s.append( n, ' ' ) );
}

This function does not make silly and unnecessary allocation of memory. So it is very efficient and robust. It has consistent interface with other functions of std::basic_string and has no side effects with undefined behaviour as the previous implementation of the function.

Enjoy!:)


вторник, 8 октября 2013 г., 9:12:19 UTC+4 пользователь Rosario1903 написал:
> On Mon, 7 Oct 2013 13:23:40 -0700 (PDT), Vlad from Moscow
>

Rosario1903

unread,
Oct 8, 2013, 4:53:55 AM10/8/13
to
On Mon, 07 Oct 2013 21:29:51 +0200, Rosario1903 wrote:

who know if there are memory leak?...

#include <iostream>
#include <cstdlib>

using namespace std;

#define u32 unsigned
#define u8 unsigned char
#define i8 char
#define F for
#define R return

class mya{
public:
~mya(){free(arr);}
mya(){arr=(u8*) malloc(15);
if(arr==0) exit(-1);
s=15;
}

mya(u32 c)
{if(c>0xFFFF) exit(-1);
arr=(u8*)malloc(c);
if(arr==0) exit(-1);
s=c;
}

mya(u8* c)
{u32 v, i;
if(c==0)
{v=1;}
else {v=strlen((i8*)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;
}

mya& operator=(const mya& r)
{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;
}

mya& operator=(u8* rs)
{u32 i, len, len1;

if(rs==0) exit(-1);
len=strlen((i8*)rs);
if(len>0xFFFFF) exit(-1);
len1=len+1;

if(s<len1)
{free(arr);
arr=(u8*) malloc(len1);
if(arr==0) exit(-1);
s=len1;
}
F(i=0; i<len1; ++i)
arr[i]=rs[i];
R *this;
}


/* lo chiamano costruttore di copia mha...
dicono che serve in:
mya b, a=b;
spero che la memoria nn sia gia' inizializzata
*/
mya(const mya& r)
{u32 i;
arr=(u8*)malloc(r.s);
if(arr==0) exit(-1);
s=r.s;
F(i=0; i<s; ++i)
arr[i]=r.arr[i];
}

friend ostream& operator<<(ostream& os, mya& ma)
{u32 i;
if(ma.s!=0)
{F(i=0; i<ma.s-1; ++i)
{if(ma.arr[i]==0) os<<" ";
else os<<ma.arr[i];
}
R os<<ma.arr[i];
}
else R os;
}

void shiftd(mya& 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;
}
}

void shiftm(mya& ma, u32 pos)
{u32 i, j, k;
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 */
/* | shiftm 3*/
F(i=0; i<pos; ++i)
arr[i]=0;
k=ma.s-pos;
F(j=0; j<k; ++j,++i)
arr[i]=ma.arr[j];
F(;i<s;++i)
arr[i]=0;
}
}


friend mya* forCompilerMya(u32 a);

friend mya& operator<<(mya& ma, u32 pos)
{mya *b;
b=forCompilerMya(15);
(*b).shiftd(ma, pos);
R *b;
}

friend mya& operator>>(mya& ma, u32 pos)
{mya *b;
b=forCompilerMya(15);
(*b).shiftm(ma, pos);
R *b;
}

friend mya& operator|(mya& ma, u32 c)
{mya *b;
b=forCompilerMya(15);
*b=ma;
b->arr[0]|=c;
R *b;
}



friend mya& operator^(mya& ma, mya& mb)
{mya *b;
u32 M, m, i;
M=ma.s>mb.s? ma.s: mb.s;
m=ma.s>mb.s? mb.s: ma.s;

b=forCompilerMya(M);
F(i=0; i<m; ++i)
b->arr[i]=ma.arr[i]^mb.arr[i];
F( ; i<M; ++i)
b->arr[i]=0;
R *b;
}


u32 s;
u8 *arr;
};

mya **bi=0;
u32 membi=0;
u32 index=0;

void fill_bi(mya* a)
{mya *r, **j;
u32 i;
if(index<=membi)
{if(membi>0xFFFFF) exit(-1);
i=membi+128; /* 128 0..127 */
j=(mya**)realloc(bi, i*sizeof *j);
if(j==0) exit(-1);
bi=j; membi=i;
}
bi[index]=a;
++index;
}

void zero_bi(void)
{mya *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;
}

void free_bi(void)
{zero_bi(); free(bi); bi=0; membi=0;}

mya* allocMya(u32 a)
{mya *b;
if(a>0xFFFF) exit(-1);
b=(mya*)malloc(sizeof *b);
if(b==0) exit(-1);
b->arr=(u8*)malloc(a);
if(b->arr==0)exit(-1);
b->s=a;
R b;
}

mya* forCompilerMya(u32 a)
{mya *b;
b=allocMya(a);
fill_bi(b);
R b;
}

mya& f(void)
{mya a((u8*)"1 2 3 4"), *b;
b=forCompilerMya(15);
*b=a;
R *b;
}


int main(void)
{mya v((u8*)"this and that "), ma, b, c[40];
u32 i, *w;
u8 *cs="A0CDEFGHILMN";

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(); zero_bi();
cout<<"b="<<b<<"\n";
F(i=0; i<4; ++i)
{c[i]=cs;
++cs[0];++cs[1];++cs[2];++cs[3];
}
F(i=0; i<4; ++i)
cout<<"c["<<i<<"]=["<<c[i]<<"]\n";
b=(((c[0]>>1)|'Q')>>1|'v');
cout<<"b=["<<b<<"]\n";
cout<<"index="<<index<<"\n";
zero_bi();
c[0]= (u8*)"";
b=c[0]^c[1] ;
cout<<"index="<<index<<"\n";

cout<<"b="<<b<<"\n";

free_bi();

R 0;
}


Ian Collins

unread,
Oct 8, 2013, 4:57:09 AM10/8/13
to
Rosario1903 wrote:
> On Mon, 07 Oct 2013 21:29:51 +0200, Rosario1903 wrote:
>
> who know if there are memory leak?...
>
> #include <iostream>
> #include <cstdlib>
>
> using namespace std;
>
> #define u32 unsigned
> #define u8 unsigned char
> #define i8 char
> #define F for
> #define R return

Why don't you go back to trolling on c.l.c?

--
Ian Collins

Rosario1903

unread,
Oct 8, 2013, 5:14:04 AM10/8/13
to
On Tue, 08 Oct 2013 10:53:55 +0200, Rosario1903
<Ros...@invalid.invalid> wrote:

>
>mya **bi=0;
>u32 membi=0;
>u32 index=0;
>
>void fill_bi(mya* a)
>{mya *r, **j;
> u32 i;
> if(index<=membi)
^^^^^^^^^^^^^^^

Rosario1903

unread,
Oct 8, 2013, 5:33:55 AM10/8/13
to
how all you are smart :)
if continue in this way there would be nobody would understand C++
code really [means can decompose it for find the micro instructions it
is composed]

Ian Collins

unread,
Oct 8, 2013, 5:40:30 AM10/8/13
to
What have your stupid cryptic macros and C code wrapped up as C++ got to
do with understanding C++?

--
Ian Collins

Rosario1903

unread,
Oct 8, 2013, 5:45:34 AM10/8/13
to
On Mon, 7 Oct 2013 23:49:47 -0700 (PDT), Vlad from Moscow
<vlad....@mail.ru> wrote:

>No problem!
>
>The correct definition of the function looks the following way
>
>std::string & shift_left( std::string &s, std::string::size_type n = 1 )
>{
> return ( s.erase( 0, n ).append( n, ' ' ) );
>}
>
>Or if you do not like when two operations are written
>in one line you can rewrite it as
>
>std::string & shift_left( std::string &s, std::string::size_type n = 1 )
>{
> s.erase( 0, n );
>
> return ( s.append( n, ' ' ) );
>}
>
>This function does not make silly and unnecessary allocation
>of memory. So it is very efficient and robust. It has consistent
>interface with other functions of std::basic_string and has no side
>effects with undefined behaviour as
>the previous implementation of the function.
>
>Enjoy!:)

sorry i never had used the C++ string library so i not know...

but the allocation of mem could be in "s.append( n, ' ' )"
and in the copy the result "s" the same, that routine return with
the "=" operator in b=shift_left(s)

David Brown

unread,
Oct 8, 2013, 7:19:43 AM10/8/13
to
Has it never occurred to you that the main reason you make so many
mistakes in your code is that you write such unintelligible crap? Scrap
the stupid macros, find the space bar on your keyboard, and use
identifiers that have meaning. Maybe you'll find that when you can read
what you write, you will have fewer mistakes. One day you may even be
able to write code that other people can read too!

Öö Tiib

unread,
Oct 8, 2013, 8:06:34 AM10/8/13
to
On Monday, 7 October 2013 21:00:26 UTC+3, Vlad from Moscow wrote:
> You are wrong. You omit the important characteristic of arrays that they
> have fixed sizes.

Your top posting that does not even quote where you think I am wrong
(just "generally wrong"?) indicates that you are actually just trolling
and not serious. Why such low traffic Usenet group? Are you hurt? If so
stay here, we are kind, do not attempt any "epic edit wars" in Wikipedia:

http://en.wikipedia.org/wiki/Variable-length_array

> They are unable to add new elements orto delete existent elements.

http://en.wikipedia.org/wiki/Dynamic_array

> It is this their characteristic that is the reason that other containers
> as for example std::vector are required.

Also that: http://en.wikipedia.org/wiki/Sparse_array

Arrays have been here since first programming languages. It does not
matter that one popular C++ template implementing sparse array of Ts is
named as 'boost::numeric::ublas::mapped_vector<T>' by its authors. It is
an array. Redefining the fundamental blocks of computer science takes lot
more than just saying that "you are wrong". :D

Vlad from Moscow

unread,
Oct 8, 2013, 8:50:24 AM10/8/13
to
Before something saying about C++ you at first need to learn C++ and what are arrays in C++. One more arrays are not classes in C++. They have fixed sized at compile time that must be specified by constant expressions.

All the stupidy you wrote here you can redirect the same dumbs as you are.

вторник, 8 октября 2013 г., 16:06:34 UTC+4 пользователь Öö Tiib написал:

Vlad from Moscow

unread,
Oct 8, 2013, 8:59:54 AM10/8/13
to
And please at least one time in your life read the C++ Sandard what are arrays in C++. And for example do not mix up arrays with class std::array because the last is not an array.:)


вторник, 8 октября 2013 г., 16:06:34 UTC+4 пользователь Öö Tiib написал:

David Brown

unread,
Oct 8, 2013, 9:10:41 AM10/8/13
to
On 08/10/13 14:50, Vlad from Moscow wrote:
> Before something saying about C++ you at first need to learn C++ and
> what are arrays in C++. One more arrays are not classes in C++. They
> have fixed sized at compile time that must be specified by constant
> expressions.
>
> All the stupidy you wrote here you can redirect the same dumbs as you
> are.
>

Please fix your top-posting.

Please get a real newsreader and use a real Usenet server. If you must
use google groups, please learn to do so properly (yes, I know it's hard
- but it is possible).

Please learn the popular social convention of familiarising yourself
with a group before bursting in with an "I know everything" attitude and
insulting the experts that have been there for years. On the basis of
demonstrated experience and knowledge, if Öö said that in C++ the sky is
green while /you/ claimed it was blue, I'd trust Öö.


Back to the point in question - you apparently don't know what an
"array" is, and think the word means specifically a statically allocated
fixed size C-style array. In the real world, an "array" is a list of
items of some sort. It does not have to be fixed size, it does not have
to have a fixed type for the contained items, it does not have to be
indexed (and certainly not just by integers - "associative arrays" are
very popular).

Vlad from Moscow

unread,
Oct 8, 2013, 9:29:07 AM10/8/13
to

вторник, 8 октября 2013 г., 16:06:34 UTC+4 пользователь Öö Tiib написал:
You simply do not know what are arrays in C++. And template classes you are referencing are not arrays. They are classes. Classes and array are two totally different notions in C++. Moreover for example in C there is no classes.:)

As I said you should at least one time in you life read the C++ Standard that to know at last what are arrays in C++.

Vlad from Moscow

unread,
Oct 8, 2013, 9:42:55 AM10/8/13
to
If you do not know what is array in C/C++ it is your personal problem. But I am not going to read the next stupidy of the next dumb. Moreover you should at least know that there is no special type of arrays in C++ that differs from arrays in C. It is the same notion in the both languages.
In the C++ TSandard arrays are described in section 8.3.4 Arrays while in the C TSandard they are described in sections 6.2.5 Types and 6.5.2.1 Array subscripting.

For example in the C Standard there is written

— An array type describes a contiguously allocated nonempty set of objects with a particular member object type, called the element type

All what you imagine yourself about arrays has nothing common with notions of arrays defined in C and C++ Standards. It is only your fantasies.



вторник, 8 октября 2013 г., 17:10:41 UTC+4 пользователь David Brown написал:

Öö Tiib

unread,
Oct 8, 2013, 10:39:13 AM10/8/13
to
On Tuesday, 8 October 2013 16:42:55 UTC+3, Vlad from Moscow wrote:
> In the C++ TSandard arrays are described in section 8.3.4

Yes the raw arrays but for example the "Numeric arrays" of C++ library
are described in 26.6 of C++ Standard. Why you call it "TSandard"?

Also note that being wrong in lot of posts does not achieve any higher
qualities of wrongness.

David Brown

unread,
Oct 8, 2013, 10:45:09 AM10/8/13
to
Hey, you got your posting right! You will find a lot more people will
talk to you now. All you need to do is change your abusive and
argumentative attitude, and stop trying to dictate to people that have
been doing this stuff probably from before you were born.

We all know what C-style arrays are in C++. We know of their
capabilities and limitations. Most of us also know what the generic
term "array" means, and what classes implement arrays, and when a class
is an array or not.

Once you have understood the difference between the specific C-style
arrays, and the generic term array referring to a particular type of
container, then we can make progress (probably by ending this thread).

Vlad from Moscow

unread,
Oct 8, 2013, 10:50:05 AM10/8/13
to
вторник, 8 октября 2013 г., 18:39:13 UTC+4 пользователь Öö Tiib написал:
One more if you are unsable to understand from the first time. The notion of array is well defined in C++ Standard. It is a derived type that has a special syntax for definition of objects of this type.

std::valarray and as for example std::array are not arrays. They are template classes. For example valarray is declared the following way

template<class T> class valarray;

Their names are simply some conventional names that help users to understand what they are designed for. They can have any other names as any other classes have. If for example you will name some you class as giraffe it does not mean that giraffe is your class.

Vlad from Moscow

unread,
Oct 8, 2013, 11:01:38 AM10/8/13
to
вторник, 8 октября 2013 г., 18:45:09 UTC+4 пользователь David Brown написал:
The problem is that you and similar to you are simply trolls.

When I pointed out that std::string is not an array I meant that if the original assignment says to write program using arrays when you should use an array and not some type of a container. Because arrays have special methods that you can apply to them and has some restrictions. So the code written for arrays will differ from the code written for example for std::string. At least arrays have no methods such as size() or erase().

I do not see any sense to feed such trolls as you any more. So you may continue your word diarrhea without me.

Rosario1903

unread,
Oct 8, 2013, 11:09:09 AM10/8/13
to
On Tue, 08 Oct 2013 16:45:09 +0200, David Brown wrote:

>On 08/10/13 15:29, Vlad from Moscow wrote:
>>
>> ???????, 8 ??????? 2013 ?., 16:06:34 UTC+4 ???????????? �� Tiib
>> ???????:
for me array are only raw array...
something as

char a[59], *a="1234", a[]={1,2,3,4,0} etc
or the mem malloc give to a pointer as
int *b;

b=malloc(15*sizeof *b)
if b!=0
b point to one array of 4 int element
etc

Rosario1903

unread,
Oct 8, 2013, 11:15:35 AM10/8/13
to
On Tue, 08 Oct 2013 17:09:09 +0200, Rosario1903
<Ros...@invalid.invalid> wrote:
>char a[59], *a="1234", a[]={1,2,3,4,0} etc
>or the mem malloc give to a pointer as
>int *b;
>
>b=malloc(15*sizeof *b)
>if b!=0
>b point to one array of 4 int element
^^^^^^
>etc

b array of 15 int elements
yes i make error even in simple points
it is a miracle how the compiler compile and the cpu execute

Vlad from Moscow

unread,
Oct 8, 2013, 11:22:52 AM10/8/13
to
вторник, 8 октября 2013 г., 19:09:09 UTC+4 пользователь Rosario1903 написал:
You are right. The notion of array is well defined in C/C++. It is a derived type that has special syntax and semantic of declarations of its objects.

For example name valaaray is simply a name of a template class. You may define your own classes with the same name valarray that will have nothing common with the C/C++ notion of arrays. For example

#include <iostream>

template <class T = void>

struct valarray
{
valarray()
{
std::cout << "Hello, World\n";
}
};

namepsace OneMore
{
template <size_t N = 3>
struct valarray
{
valarray()
{
for ( size_t i = 0; i < N; i++ ) std::cout << "Hello, World\n";
}
};
}

int main()
{
valarray<> v1;
OneMore::valarray<> v2;
}

These classes have nothing common with the notion of array in C++. You may use any names for your classes if they are not reserved words of the language. And even you will name some your class as array it does not mean that it is array.:)

Geoff

unread,
Oct 8, 2013, 11:23:48 AM10/8/13
to
On Tue, 08 Oct 2013 10:53:55 +0200, Rosario1903 <Ros...@invalid.invalid> wrote:

>who know if there are memory leak?...
>

tl;dr

Geoff

unread,
Oct 8, 2013, 11:26:18 AM10/8/13
to
Perhaps you should stop writing unintelligible crap and start writing
in the language of the compiler. Then you will won't be correcting
your own code twenty minutes after you write it.

David Brown

unread,
Oct 8, 2013, 11:29:51 AM10/8/13
to
On 08/10/13 17:01, Vlad from Moscow wrote:
> вторник, 8 октября 2013 г., 18:45:09 UTC+4 пользователь David Brown
> написал:
>>
>>
>> Once you have understood the difference between the specific
>> C-style
>>
>> arrays, and the generic term array referring to a particular type
>> of
>>
>> container, then we can make progress (probably by ending this
>> thread).
>

I was wrong about you fixing your posting style - you've stopped
top-posting, which is good, but you are still getting Google Group's
double line spacing on quoted text, and completely wrong line lengths.

>
> The problem is that you and similar to you are simply trolls.

A "troll" provokes argument for argument's sake. You see them in this
group sometimes, but neither I nor the others who have disagreed with
you are trolls. We are trying to correct your mistakes - but you are so
determined to stay ignorant that it is probably impossible.

>
> When I pointed out that std::string is not an array I meant that if
> the original assignment says to write program using arrays when you
> should use an array and not some type of a container. Because arrays
> have special methods that you can apply to them and has some
> restrictions. So the code written for arrays will differ from the
> code written for example for std::string. At least arrays have no
> methods such as size() or erase().

The OP gave no information about any particular type of array.
Sometimes a string can be treated as an array of characters, and
sometimes an array of characters can be treated as a string (noting, of
course, that there are many types of "string" in C++).

You are hung up on the idea that "array" means only specific C-style
arrays. This is simply not true, and the OP certainly did not restrict
the question to that kind of array.

Incidentally, C-style arrays do not have "methods" of any sort, and they
/are/ a type of container.

Vlad from Moscow

unread,
Oct 8, 2013, 11:45:04 AM10/8/13
to
вторник, 8 октября 2013 г., 19:29:51 UTC+4 пользователь David Brown написал:
> On 08/10/13 17:01, Vlad from Moscow wrote:
>
>
> The OP gave no information about any particular type of array.
>
> Sometimes a string can be treated as an array of characters, and
>
> sometimes an array of characters can be treated as a string (noting, of
>
> course, that there are many types of "string" in C++).
>

You even do not understand what "any particular type of array" means in C/C++. Any particulat type of an array means simply the type of array elements and number of dimensions and sizes of the array and nothing more.


>
>
> You are hung up on the idea that "array" means only specific C-style
>
> arrays. This is simply not true, and the OP certainly did not restrict
>
> the question to that kind of array.
>

There is only ONE definition of the notion of arrays in C/C++. Do you have not understood? I am repeating one more for such trolls as you: there is only one notion of arrays defined in C/C++. Do you have not understood yet? Do you need that I repeat one more?

Martin Shobe

unread,
Oct 8, 2013, 12:06:51 PM10/8/13
to
This is probably pointless, but here goes.

On 10/8/2013 1:38 AM, Vlad from Moscow wrote:
> It is simply is very silly and bad code. The memory allocated and deallocated at least two times.And this code demonstrates only one intention that the author is unable to write programs.
>
> In this simple function that contains only two lines in the body the author made three serious errors.
>
> First the function has undefined behaviour because its second parameter is defined as int. So any value of type std::string::size_type that can not be fit into int will result in undefined behaviour of the function.

Technically that's a problem with the caller.

> Second, the interface of the function is inconsistent with the interface of std::basic_string. See the description of std::basic_string in the C++ Standard.

And that's a problem because?

> Third, this function allocates and deallocates memory at least two times. As a result 1) the memory will be fragmented; 2) it is possible that allocating of memory will fail for large strings.
> And it is a stupidy to allocate a new memory then the original string has enough memory that to do the operation "in place".

On the implementations I have available, this function
allocated/deallocated memory at most once. For the small n in the
example, it didn't perform any memory allocations.

Still, I do find I prefer the following.

void shift_left(string & s, int n)
{
s.erase(0, n);
s.append(n, ' ');
}

This results in zero allocations regardless of n and I find it clearer.

[snip]

Martin Shobe

David Brown

unread,
Oct 8, 2013, 12:31:14 PM10/8/13
to
You can repeat your misconceptions as much as you want - no one else
will accept them.

There is no such language as C/C++.

<http://en.wikipedia.org/wiki/Array#In_computer_science>

At some point, I hope you will realise that it makes sense to use the
same terms as other people. It makes communication /so/ much easier.

Vlad from Moscow

unread,
Oct 8, 2013, 12:45:50 PM10/8/13
to
вторник, 8 октября 2013 г., 20:06:51 UTC+4 пользователь Martin Shobe написал:
> This is probably pointless, but here goes.
>
>
>
> On 10/8/2013 1:38 AM, Vlad from Moscow wrote:
>

> Technically that's a problem with the caller.


When you make "technically" problems for callers it just means that you wrote a bad code and nothing more.
In fact you simply specified incorrect type because class std::string specially declared the corresponding type size_type for such parameters that specify number of elements of a string. But you ignored the interface of the class. This says about your very lower qualification.


> And that's a problem because?

You should keep consistent interface among funcrions. This makes it easy to use them and intuitively more clear. Such function will be intershangeable in their usage.


Consider the following simple example. Let assume that you wrote

std::cout << s.erase( 0, n ) << std::endl;

But then you (or somebody else after you) decided that instead of s.erase( 0, n ) there must be shift_left( s, n ).
If you had consistent interface then all you need is to substitute s.erase( 0, n ) for shift_left( s, n )

std::cout << shift_left( s, n ) << std::endl;

When you have a consistent interface of functions then it is much easier to support programs.


>
> On the implementations I have available, this function
>
> allocated/deallocated memory at most once. For the small n in the
>
> example, it didn't perform any memory allocations.
>

The original function I pointed out allocates and deallocate memory at least two times irrespective of the value of n. First of all it calls the constructor

std::string( n, ' ' )

that allocates memory.

Secondly operator + again allocates memory to accomodate elements of this temporary object with elements of the original string. And thirdly the memory occupied by the original string has to be substituted for the new one memory.

>
>
> Still, I do find I prefer the following.
>
>
>
> void shift_left(string & s, int n)
>
> {
>
> s.erase(0, n);
>
> s.append(n, ' ');
>
> }
>
>
>
> This results in zero allocations regardless of n and I find it clearer.
>
>
>
> [snip]


I always wonder the talant of others to substitute a good code for a more bad code.:):)

I already showed how the function shall be defined. The only improvment that could be done is relative the second parameter because usually such a parameter can be assigned std::string::npos that means that all elements of the string must be processed.

So I would rewrite my original solution the following way


std::string & shift_left( std::string &s, int n = 1 )
{
if ( n == std::string::npos ) n = s.size();

Vlad from Moscow

unread,
Oct 8, 2013, 12:52:49 PM10/8/13
to
вторник, 8 октября 2013 г., 20:31:14 UTC+4 пользователь David Brown написал:
> You can repeat your misconceptions as much as you want - no one else
>
> will accept them.
>


If you name definitions in the C++ Standard as misconceptions then it means only that you are an idiot. I advice you to read the C++ standard and do not substitute its definitions with your owns.

>
> There is no such language as C/C++.
>

Nobody said that there is such a language as C/C++. It means simply any of thelanguages either C or C++.:)

Martin Shobe

unread,
Oct 8, 2013, 2:06:18 PM10/8/13
to
On 10/8/2013 11:45 AM, Vlad from Moscow wrote:
> вторник, 8 октября 2013 г., 20:06:51 UTC+4 пользователь Martin Shobe написал:
[snip]

>> On the implementations I have available, this function
>>
>> allocated/deallocated memory at most once. For the small n in the
>>
>> example, it didn't perform any memory allocations.
>>
>
> The original function I pointed out allocates and deallocate memory at least two times irrespective of the value of n. First of all it calls the constructor
>
> std::string( n, ' ' )
>
> that allocates memory.

It may or may not allocate memory. On the implementations I have access
to, the small-string optimization has been implemented, so
std::string(n, ' ') only allocates memory for "large" n.

> Secondly operator + again allocates memory to accomodate elements of this temporary object with elements of the original string. And thirdly the memory occupied by the original string has to be substituted for the new one memory.

Those had been optimized away.

[snip]

Martin Shobe

Vlad from Moscow

unread,
Oct 8, 2013, 2:46:16 PM10/8/13
to
вторник, 8 октября 2013 г., 22:06:18 UTC+4 пользователь Martin Shobe написал:
> On 10/8/2013 11:45 AM, Vlad from Moscow wrote:
>
> > вторник, 8 октября 2013 г., 20:06:51 UTC+4 пользователь Martin Shobe написал:
>
> [snip]
>
>
>
> >> On the implementations I have available, this function
>
> >>
>
> >> allocated/deallocated memory at most once. For the small n in the
>
> >>
>
> >> example, it didn't perform any memory allocations.
>
> >>
>
> >
>
> > The original function I pointed out allocates and deallocate memory at least two times irrespective of the value of n. First of all it calls the constructor
>
> >
>
> > std::string( n, ' ' )
>
> >
>
> > that allocates memory.
>
>
>
> It may or may not allocate memory. On the implementations I have access
>
> to, the small-string optimization has been implemented, so
>
> std::string(n, ' ') only allocates memory for "large" n.
>

The notion of "large" or "small" strings are very conditional. In this concrete case the large string can be considered as any string that has size greater than for example 10 symbols.:)
Try to use expression

std::cout << sizeof( std::string ) << std::endl;

and you will see what the "large" string means in realty.


>
>
> > Secondly operator + again allocates memory to accomodate elements of this temporary object with elements of the original string. And thirdly the memory occupied by the original string has to be substituted for the new one memory.
>
>
>
> Those had been optimized away.
>

it is not guaranteed by the Standard.

>
>
> [snip]
>
>
>
> Martin Shobe

Rosario1903

unread,
Oct 8, 2013, 3:15:36 PM10/8/13
to
On Mon, 7 Oct 2013 00:07:52 -0700 (PDT), alf.p.steinbach wrote:
>On Monday, October 7, 2013 8:03:31 AM UTC+2, Rosario1903 wrote:
>> On Sun, 06 Oct 2013 18:59:06 +0200, Rosario1903 wrote:

>In C++ better declare variables as near their first use as possible.
>
>In this case, write e.g. "for( u32 i = 0, ...".
>
>However, as mentioned, it's even better to write just "for( int i = 0, ...".

i'm not agree

i follow the law "declare all that one use at the start of routine
and initialize it near one use it"


>> cout<<"at start v=["<<v <<"]\n";
>> ma.shiftd(v, 3);
>> cout<<"at end ma=["<<ma<<"]\n";
>>
>> for(i=0;i<12;++i)
>> {ma.shiftd(ma, 1);
>> cout<<"at end ma=["<<ma<<"]\n";
>> }
>
>> return 0;
>
>In both C++ and C it's now unnecessary to return 0 from main,
>as that's the default.
>
>It has always been the default in C++.
>
>However, many programmers still prefer to indicate the "main"
>return value explicitly. For that purpose it can be a good idea
>to use the symbolic values EXIT_SUCCESS and EXIT_FAILURE from
><stdlib.h>. In this case, EXIT_SUCCESS,
>which is what 0 means in this context.
>
>> }
>
>As a general comment, since myarray does not take charge of
>copying -- it does not declare any copy constructor or assignment
>operator -- any use of it that inadvertently invokes copying,
>will in general cause the same memory to be deallocated
>twice (via the free call in the destructor), invoking
>Undefined Behavior, such as e.g. a crash... :-(

yes i make i try of double free: crash

i disagree in something and agree in other
but i think is not important

thank you for the long and good post

Vlad from Moscow

unread,
Oct 8, 2013, 3:26:56 PM10/8/13
to
вторник, 8 октября 2013 г., 23:15:36 UTC+4 пользователь Rosario1903 написал:
> On Mon, 7 Oct 2013 00:07:52 -0700 (PDT), alf.p.steinbach wrote:
>
> >On Monday, October 7, 2013 8:03:31 AM UTC+2, Rosario1903 wrote:
>
> >> On Sun, 06 Oct 2013 18:59:06 +0200, Rosario1903 wrote:
>
>
>
> i'm not agree
>
>
>
> i follow the law "declare all that one use at the start of routine
>
> and initialize it near one use it"
>

There is no such a law.:) Declarations of all used variables in a function at its very beginning only confuse readers because they do not know yet where and how and whether these variables are used.

Scott Lurndal

unread,
Oct 8, 2013, 4:49:39 PM10/8/13
to
Vlad from Moscow <vlad....@mail.ru> writes:
>=D0=B2=D1=82=D0=BE=D1=80=D0=BD=D0=B8=D0=BA, 8 =D0=BE=D0=BA=D1=82=D1=8F=D0=
>=B1=D1=80=D1=8F 2013=C2=A0=D0=B3., 23:15:36 UTC+4 =D0=BF=D0=BE=D0=BB=D1=8C=
>=D0=B7=D0=BE=D0=B2=D0=B0=D1=82=D0=B5=D0=BB=D1=8C Rosario1903 =D0=BD=D0=B0=
>=D0=BF=D0=B8=D1=81=D0=B0=D0=BB:
>> On Mon, 7 Oct 2013 00:07:52 -0700 (PDT), alf.p.steinbach wrote:
>>=20
>> >On Monday, October 7, 2013 8:03:31 AM UTC+2, Rosario1903 wrote:
>>=20
>> >> On Sun, 06 Oct 2013 18:59:06 +0200, Rosario1903 wrote:
>>=20
>>=20
>>=20
>> i'm not agree
>>=20
>>=20
>>=20
>> i follow the law "declare all that one use at the start of routine
>>=20
>> and initialize it near one use it"
>>=20
>
>There is no such a law.:) Declarations of all used variables in a function =
>at its very beginning only confuse readers because they do not know yet whe=
>re and how and whether these variables are used.

There are coding guidelines at all development shops. Some codify the
source location for declarations such that they are declared at the
beginning of any basic block (e.g. following a '{') instead of interspersing
declarations willy-nilly throughout a function. While C++ allows
willy-nilly declarations, it in no way requires them, and many consider
them to be "confusing", particularly in larger function bodies. When declared
at the start of a block, the maintenance programmer will always know exactly
where to look in a function for the declaration, and many editing tools have
short-cuts to move the cursor to the start of a block ('[[' in vi).

So there is no law either way; it is purely a matter of preference and YPMV.

Vlad from Moscow

unread,
Oct 8, 2013, 5:56:32 PM10/8/13
to
среда, 9 октября 2013 г., 0:49:39 UTC+4 пользователь Scott Lurndal написал:
> There are coding guidelines at all development shops. Some codify the
>
> source location for declarations such that they are declared at the
>
> beginning of any basic block (e.g. following a '{') instead of interspersing
>
> declarations willy-nilly throughout a function. While C++ allows
>
> willy-nilly declarations, it in no way requires them, and many consider
>
> them to be "confusing", particularly in larger function bodies. When declared
>
> at the start of a block, the maintenance programmer will always know exactly
>
> where to look in a function for the declaration, and many editing tools have
>
> short-cuts to move the cursor to the start of a block ('[[' in vi).
>
>
>
> So there is no law either way; it is purely a matter of preference and YPMV.

The the maintenance programmer should look the code where the variables are used. And if he will see numerous variable declarations and he can say nothing what they mean where they used and so on it will be only confused.
I advice you to rewrite your coding guidelines. They are simply a nonsense written by people who understand nothing in programming. Moreover if a function a big enough that it can fit itself one screen you forgot what variables were declared and how they were declared. You will need to scroll screns forward and back that to see the variable declarations.
So never repeat such ninsenses any more that you wrote for code guidelines.
It is loading more messages.
0 new messages