C++ problem

Daniel Brewer dan.brewer at gmail.com
Fri Aug 6 01:18:28 PDT 2004

On Fri, 06 Aug 2004 02:29:03 -0300, michael <michael8110 at terra.com.br> wrote:
> hello,i've been quite happily tinkering with C++ for the last few
> months,and i can't remember anything more enjoyable and stimulating in a
> long time,which probably gives away ,well never mind.Problem is as
> follows:i'm trying to build a linked list database,so obviously i'll need
> to put in some text,and that's where things are getting stuck.For
> example,the below code,that would be more or less what i'd do to fill the
> nodes with data,
> #include <iostream.h>
> class car
> {public:
> char itsName[20];
> };
> int main()
> {char a[20]="citroen";
> car c;
> c.itsName=a;  //line 10
> cout<<a;
> return 0;
> }
> returns
> test.cpp: In function `int main()':
> test.cpp:10: error: ISO C++ forbids assignment of arrays (WHY? i'm just
> assigning a pointer here )
> likewise.
> c.itsName[20]="citroen";
> begets
> test.cpp:10: error: invalid conversion from `const char*' to `char' (CAN'T
> see anything wrong here either,isn't this the usual way of assigning a
> char array?)
> finally
> c.itsName[20]=a[20];
> compiles and produces the expected
>    michael ~ # ./a.out
> citroen
> Would someone be so kind as to shed some light on this confusing state of
> affairs?I mean,if it's ok to assign "citroen" to a[20] ,why not then also
> to c.itsName[20] ?Thank you!

I am no expert.  Not sure exactly but I expect it will have something
to do with the fact that c-arrays are really just pointers.  By doing
[20] you are basically saying how much memory is needed.   SO it might
have something to do with that.

Sorry for asking, but why don't you just use the standard string class
for this?  It does all the work for you! (#include <string>)

Also another thing.  It normally is not the done thing that you assign
class variables directly outside of the class.   It is better to have
a function to do it e.g.

void car::setName(char[20] inName)
       for(i=0;i<20;i++) itsName[i]=inName[i];

Not sure if that would work (I have my doubts).

Hope that helps.   Use the string class.


Daniel Brewer

More information about the lfs-chat mailing list