C++ problem

Wolfgang Landauer w.landauer at gmx.de
Sat Aug 7 09:00:30 PDT 2004


michael killed the keyboard with:

> Daniel,thanks a lot,in fact using 'string' did it.Björn,very nice to
> read you again,i still have to look at your message more closely,but
> what is really difficult for me to understand at this point is why
> #include<iostream>
> using namespace std;
> int main()
> {char a[20]="citroen";
> cout<<a;
> return 0;
> }
> 
> produces
> --

why do you place a sig delimiter in the middle of your message?

> michael ~ # ./a.out
> citroen
> 
> and
> 
> #include<iostream>
> using namespace std;
> class car
> {public:
> char itsName[20];
> };
> 
> int main()
> {car c;
> c.itsName[20]="citroen";

why do you want to write "citroen" in the 21st Element of the char array
itsName if it only has 20 Elements (counting starts at zero) and one
Element can only hold one char and not eight?

> cout<<c.itsName;
> return 0;
> }
> 
> returns this error message
> 
> michael ~ # g++ ./test2.cpp
> test2.cpp: In function `int main()':
> test2.cpp:12: error: invalid conversion from `const char*' to `char'

"citroen" is a pointer to a string constant it really can be converted to
a char

> (ISN'T it the same to write char a[20]="citroen"; and
> c.itsName[20]="citroen"; since itsName[20] is a char in the class
> declaration?I tried using string,as Daniel and you suggested and
> everything worked fine,but i still would like to see through this.Thanks
> again.

when you use string the the assignment operator is already overloaded for
you and does all the things in the background like allocating dynamic
memory...

try to get a good c++ tutorial and learn all the things. Especially char
arrays and strings dynamic memory allocation and memory leaks als well as
pointers.

Wolfgang
-- 
   .-.   This is Linux Country.
   /v\   On a quiet night, you
 /(   )\ can hear Windows reboot.
  ^^ ^^  LFS-No.: 120



More information about the lfs-chat mailing list