Thread: c++ wtf...

  1. #1
    Registered User
    Join Date
    Dec 2006

    c++ wtf...

    int len [5];
    this prints 20....where does 20 come from

  2. #2
    The Right Honourable psychopath's Avatar
    Join Date
    Mar 2004
    Where circles begin.
    An int is 4 bytes, and you've declared an array of 5 ints. So 4*5=20 bytes.
    M.Eng Computer Engineering Candidate
    B.Sc Computer Science

    Robotics and graphics enthusiast.

  3. #3
    Registered User
    Join Date
    Dec 2006
    so how do i get the length of the array besides sizeof() * 4;

    int arr [ size ];

    when i do memset, i have to do
    memset( arr, 0 , size*4 ) ?

  4. #4
    Registered User
    Join Date
    May 2006
    memset( arr, 0 , sizeof(arr) )
    Last edited by l2u; 12-24-2006 at 08:39 PM.

  5. #5
    Registered User
    Join Date
    Dec 2006
    and getting length of array (not number of bytes)? (besides sizeof / 4)

  6. #6
    Registered User
    Join Date
    Jan 2005
    sizeof(arr) / sizeof(arr[0])

    Although that doesn't work if you have passed the array to a function or have just a pointer to it. In those cases, you need to keep track of the size yourself.

    In C++, it is generally better to use vector (or std::tr1::array) which remember their own sizes.

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    > memset( arr, 0 , size*4 ) ?
    So what's wrong with doing
    for ( int i = 0 ; i < size ; i++ ) arr[ i ] = 0;

    memset is a very low level function which has no knowledge of types. The for loop approach is both intuitively obvious, and will continue to work on arrays of all types, not just ints.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Neck bomb kills Pizza man. WTF?
    By Govtcheez in forum A Brief History of
    Replies: 20
    Last Post: 09-03-2003, 07:40 PM
  2. no... wtf!!!?? ( Global class is 'undeclared' )
    By knave in forum C++ Programming
    Replies: 5
    Last Post: 05-10-2003, 05:41 PM
  3. wtf is wrong with msdn
    By Shadow12345 in forum A Brief History of
    Replies: 4
    Last Post: 09-29-2002, 05:59 PM
  4. Wtf??? 7/9*9 = 0???
    By Tyrael in forum C++ Programming
    Replies: 2
    Last Post: 11-13-2001, 10:41 PM