Re: getchar returns int, assign to array of char?

Discussion in 'C Programming' started by Ben Fitzgerald, Jun 27, 2003.

  1. Okay, help me out here. If I assign c straight to x[i++]:
    x[i++] = c;

    I'm incorrect because c could contain a vaule greater than
    UCHAR_MAX, but x can only hold CHAR_MIN...CHAR_MAX

    *But*, if you have (c = getchar()) != EOF) as a test in your
    while loop and getchar() "returns an unsigned char cast
    to an int, or EOF" (I got this quote from a linux man page!)
    then EOF cannot be assigned inside the loop thanks to the test
    so the former (unsigned char) will be assigned to x[i++]

    int c, i = 0;
    unsigned char x[20];

    while ((c=getchar()) != EOF && i < sizeof x - 1)
    x[i++] = c;

    Therefore, shouldn't array x simply be of type unsigned char!?
    I am agreeing with you in a roundabout way, just without the
    pointers, I think.

    What do you reckon?
    Ben Fitzgerald, Jun 27, 2003
    1. Advertisements

  2. Ben Fitzgerald

    Micah Cowan Guest

    No, c will either hold a value from 0 to UCHAR_MAX (not greater), or
    it will hold the value EOF.
    Right, but that's the problem: assigning an unsigned char to a char
    can overflow when char is a signed type.

    If you are expecting that your file is made up entirely of textual
    characters which are all representable in the char type, then you can
    perform a check such as:

    if (c > CHAR_MAX) {
    /* c can't be represented as a regular char.
    handle this as an error... */

    Otherwise, if you want these bytes to be represented exactly, you
    should follow Dan's advice.
    But, as Dan pointed out, you would then have difficulties using x with
    the Standard Library's string manipulation facilities.

    Micah Cowan, Jun 28, 2003
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.