Re: update...

From: Thomas Matthews (Thomas_MatthewsHatesSpam_at_sbcglobal.net)
Date: 10/22/03


Date: Wed, 22 Oct 2003 16:42:29 GMT

earl wrote:

> class foo
> {
> foo();
> private:
> char table[64];
> };
>
> foo::foo()
> {
> for(int index=0; index < 64; index++)
> table[index] = index;

Here you assign an "int" value (index)
into a "char" type (table[]).

In many systems, a char type is smaller than an
int type. In these systems, an "invisible" truncation
or conversion will take place. Ugly, very ugly.

Try this:
   for (char index = 0; index < 64; ++index)
     table[index] = index;

> }
>
> in the main program I do ;
>
> foo test;
>
> nothing more, just run the constructor
>
> it seems to run through the above loop coz I get 'Press any key to continue'
> then I get popup box saying test.exe has encountered a problem and needs to
> close. We are sorry for the inconvenience.
>
> If I remove the for loop in the constructor everything runs smoothly.
>
>

One item that others haven't mentioned is that you
declare the array as type "char" while you assign it
"int" values. Although many compilers may not issue a warning,
I believe it should, and you should turn up the warning levels.

In your main() program, insert the following:
   std::cout << "Size of char: " << sizeof(char) << "\n";
   std::cout << "Size of int: " << sizeof(int) << "\n";

-- 
Thomas Matthews
C++ newsgroup welcome message:
          http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq:   http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
          http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
     http://www.josuttis.com  -- C++ STL Library book


Relevant Pages

  • Re: wrong print
    ... you must be using non-standard libraries. ... int max_line_len = 1024; char **Amm,**Pss; ... char* readline; void scandir; ... Before posting for the first time to a group ALWAYS read the FAQ ...
    (comp.lang.c)
  • Re: Bitfield casting
    ... I'll assume `uint' is a typedef alias for `unsigned int'. ... int foo(char *); ... foo(&binfo); ...
    (comp.lang.c)
  • Re: Problem 77: Greedy Gift Givers
    ... char name; ... struct friend f; ... int i = 0; ... Then read the rest of the faq also. ...
    (comp.lang.c)
  • Re: [C] structures
    ... > struct student { ... > int main ... char grade; ... a.c.l.l.c-c++ FAQ mirror: http://nullptr.merseine.nu:8080/acllcc++.html ...
    (alt.comp.lang.learn.c-cpp)
  • Re: class_device_add error in SCSI with 2.6.17-rc2-g52824b6b
    ... redefined strncpy to mystrncpy (I used strncpy.S and stxncpy.S from ... int main(int argc, char **argv) ... strncat(src, letter, FOO); ...
    (Linux-Kernel)