Zero Termination

Discussion in 'Mac Programming' started by larswik, Dec 30, 2010.

  1. larswik macrumors 68000

    Sep 8, 2006
    I know you terminate a char array with '\0'

    char list[5] = {'a','b','c','d','\0');

    But do you also terminate an int array the same way?

    int list[5] = {1,2,3,4,'\0');

  2. Sander macrumors 6502

    Apr 24, 2008
    You could. But note that terminating this way is just an "agreement" which all functions in C that handle strings adhere to (such as printf, strlen, etc.), to solve the problem that you can't find out the size of an array once it's been passed to a function.

    For strings, this is a reasonable way of handling them since the null character is not a valid printable character anyway. But if you want to play the same trick with arrays of other types, you will have to make sure that "zero" is not an otherwise valid entry in your array.
  3. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    0 is a mighty common value, so eliminating it as a possible value may not work out for too long for you. INT_MAX or INT_MIN are less likely to crop up in "real" input than 0, so one of these might be better. You're still reducing the valid numbers, but you're plucking one off the end rather than the dead middle . Ultimately since there's no "standard" way to do this you might be better served sticking with lugging around a length. That's just how we do things, and we like it, dagnabbit!

  4. larswik thread starter macrumors 68000

    Sep 8, 2006
  5. balamw Moderator


    Staff Member

    Aug 16, 2005
    New England
    Looks like you got the general idea in your other recent thread, just keep the terminator outside the range of valid numbers (e.g 20 when your numbers are 0-9).

    Just wanted to point out some of the other "magic numbers" programmers like to use like 0xDEADBEEF many of which are large 32 bit numbers that can be "read" like text.

    Carrying around a length is probably the better way to do it than using any kind of terminator.


Share This Page