1

What would be the reason for out[0] = '\0'; on the main() function?

It does seem to be working without it.

Code

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define MAXTOKEN 100
enum { NAME, PARENS, BRACKETS };

int tokentype;
char token[MAXTOKEN]; /*last token string */
char name[MAXTOKEN]; /*identifier name */
char datatype[MAXTOKEN]; /*data type = char, int, etc. */
char out[1000];

void dcl(void);
void dirdcl(void);
int gettoken(void);

/*
Grammar:

    dcl:            optional * direct-dcl
    direct-dcl:     name
                    (dcl)
                    direct-dcl()
                    direct-dcl[optional size]
*/

int main() /* convert declaration to words */
{
    while (gettoken() != EOF) {    /* 1st token on line */

        /* 1. gettoken() gets the datatype from the token  */
        strcpy(datatype, token);

        /* 2. Init out to end of the line? */
        /* out[0] = '\0'; */

         /* parse rest of line */
        dcl();

        if (tokentype != '\n')
            printf("syntax error\n");

        printf("%s: %s %s\n", name, out, datatype);
    }

    return 0;
}

int gettoken(void) /* return next token */
{
    int c, getch(void);
    void ungetch(int);
    char *p = token;

    /* Skip blank spaces and tabs */
    while ((c = getch()) == ' ' || c == '\t')
        ;

    if (c == '(') {

        if ((c = getch()) == ')') {

            strcpy(token, "()");
            return tokentype = PARENS;

        } else {
            ungetch(c);
            return tokentype = '(';
        }

    } else if (c == '[') {

        for (*p++ = c; (*p++ = getch()) != ']'; )
            ;

        *p = '\0';
        return tokentype = BRACKETS;

    } else if (isalpha(c)) {

        /* Reads the next character of input */
        for (*p++ = c; isalnum(c = getch()); ) {
            *p++ = c;
        }

        *p = '\0';
        ungetch(c); /* Get back the space, tab */

        return tokentype = NAME;

    } else
        return tokentype = c;
}

/* dcl: parse a declarator */
void dcl(void)
{
    int ns;

    for (ns = 0; gettoken() == '*'; ) /* count *'s */
        ns++;

    dirdcl();

    while (ns-- > 0)
        strcat(out, " pointer to");
}

/* dirdcl: parse a direct declarator */
void dirdcl(void)
{
    int type;

    if (tokentype == '(') {

        dcl();

        if (tokentype != ')')
            printf("error: missing )\n");

    }
    else if (tokentype == NAME) /* variable name */ {
        strcpy(name, token);
        printf("token: %s\n", token);
    }
    else
        printf("error: expected name or (dcl)\n");

    while ((type = gettoken()) == PARENS || type == BRACKETS) {

        if (type == PARENS)
            strcat(out, " function returning");
        else {
            strcat(out, " array");
            strcat(out, token);
            strcat(out, " of");
        }

    }
}
4
  • 1
    Because strcat wants a NUL terminated string, but in this case (as a global variable) it is initialized to {0} Nov 2, 2016 at 19:32
  • Try entering two lines of input. Nov 2, 2016 at 19:34
  • 1
    @KeineLust it has static storage duration so it is automatically zero-initialized. Nov 2, 2016 at 19:34
  • The man page says: The strcat() function appends the src string to the dest string, overwriting the terminating null byte ('\0') at the end of dest, and then adds a terminating null byte Doesn't it mean that it does handle it without we explicitly specifying it. Btw: sorry for my silly questions. =)
    – dud3
    Nov 2, 2016 at 19:37

3 Answers 3

2

You need out[0] to be zero in order for strcat to work.

While this line

out[0] = '\0';

was required prior to the introduction of static initialization rules, it is no longer required, because static arrays, such as out[], are initialized to all zeros.

According to initialization rules of C99,

  • ...
  • if it has arithmetic type, it is initialized to (positive or unsigned) zero.
  • if it is an aggregate, every member is initialized (recursively) according to these rules.
7
  • I see, but why would it initialize the first char to \0, wouldn't something alike: strcat(out, "abc"); make out look like out = {'\0', 'a', 'b', 'c'}?
    – dud3
    Nov 2, 2016 at 19:39
  • @dud3 No, '\0' is considered null terminator, so a string with '\0' as its initial character behaves like an empty string, no matter what characters come after ''\0'`. Nov 2, 2016 at 19:40
  • Ah now I see, couldn't we simply initialize it to out[0] = ' ' instead?
    – dud3
    Nov 2, 2016 at 19:42
  • 1
    But then it would have an extra space.
    – dud3
    Nov 2, 2016 at 19:42
  • @dud3 Without default initialization setting out[0] = ' ' would require also setting out[1] = '\0', otherwise it would be unterminated. Nov 2, 2016 at 19:43
1

It is resetting the char array (aka string) to empty array. (removing junk values) like we use:

int i = 0;

before doing something like:

i += 1;

so that junk value don't add

So just '\0' in 0 index of array tells that array is completely empty and the strcat function starts appending value from 0 index, over writing the junk values in other indexes of array.

If program is working without resetting array then it means your IDE tool is doing that for you, but it is good practice to reset it.

1

In short: In this particular case it's not strictly necessary, but in many other cases that look suspiciously similar, it is, so most people do it as "good style". So why would it be necessary?

There is no such thing as "empty" memory. There is no such thing as a "length". Unless you explicitly keep track of it, or define your own.

Memory is just bytes, which are numbers from 0 to 255. Since 0 is just as valid a number as 255, there is no way to tell whether a byte is used or not. You can "add up" several bytes if you need larger numbers, but everything is built out of bytes, in the end. Text is simply mapped to a number. A couple decades ago it was decided which number represents which character. So if you see a byte with the value 32, it could be a 32. Or it could be the 32nd letter in the computer's alphabet (which is the space character).

When you receive a string and you don't know how much text you will be dealing with, what you usually do is you reserve a large block of bytes. This is what char out[1000]; above does. But how do you tell where the text ends? How much of the 1000 bytes you've already used?

Well, in the old days, some people would just declare another variable, say, int length; and keep track of how many bytes they've used so far. The designers of C went a different route. They decided to pick a very rare character and use that as a marker. They picked the character with the value 0 for that (That is not the character '0'. The character '0' actually is the 48th letter of a computer's alphabet).

So you can just look at all the bytes in your string from the start, and if a character is > 0, you know it is used. If you reach a 0 character, you know this is the end of your string. There are various advantages to either approach. An int uses 4 bytes, an additional 0-character only 1. On the other hand, if you use an int, a string can also contain a 0-character, it's just another character, nobody cares.

Whenever you write "foo" in C, what C actually does is reserve room for 4 bytes, for 'f', 'o', 'o' and for the 0 to indicate the end. When you write "" in C, what it does is reserve room for a single byte, the 0. So that you can tell that the string is empty.

So, what is memory filled with before you put something into it at startup? Well, in most cases, it is just garbage. Whatever was in that memory the last time it was used (after all, you have limited RAM, so when you quit one application on your computer, its memory can get re-used for the next app you launch after that). These will be random numbers, often outside of the range of common characters.

So, if you want strcat to see out as an empty string, you need to give it a block of memory that starts with this 0 value character. If you just leave memory like it is, there might be some random characters in it. Your buffer might contain "jbhasugaudq7e1723876123798dbkda0skno§§^^%$#-9H0HWDZmwus0/usr/local/bin" or whatever was in that memory before. If you now appended some text to it, it would think the stuff before the first 0 (which is just randomly in this place) was a valid string, and append it to that. It will only know that this string is supposed to be empty, if you put a 0 right at the start.

So why did I say it is "not strictly necessary"? Well, because in your case, out is a global variable, and global variables are special because they automatically get cleared to 0 when your application starts up (or assigned any value that you assign them when you declare them).

However, this is only true for global variables (both regular globals and static globals). So many programmers make it a habit to always initialize their blocks of bytes. That way, if someone later decides to change a global into a local variable, or copy-and-pastes the code to another spot to use with a local variable, they do not have to worry about forgetting to add this statement.

This is especially useful as random memory often contains 0 characters. So depending on what program you previously used, you might not notice you forgot the initial 0 because there happened to be one already in there. And only later, when one of your users runs this application, they get garbage at the start of their string.

Does that clarify things a bit?

8
  • Yes that did clarify a lot.
    – dud3
    Nov 2, 2016 at 23:32
  • I was unsure since the man page of strcat says: The strcat() function appends the src string to the dest string, overwriting the terminating null byte ('\0') at the end of dest, and then adds a terminating null byte, which I thought it would already handle this for us.
    – dud3
    Nov 2, 2016 at 23:33
  • When you have two strings, say "Home\0" and "work\0" (Where \0 is the 0 I talked about before), and you just append one to the other, you would get "Home\0work". C thinks a string ends at a \0, so this would be the same as \0. So that's not how strcat could work. What it instead does is delete the first \0 and then append the rest, so you get the expected "Homework". Then it appends another "\0" so you can tell that the string really ends after "work". However, the first \0 still needs to be there for strcat to know how long "Home" is.
    – uliwitness
    Nov 3, 2016 at 13:23
  • When the first word comes into your program, what you waant to do is, instead of using strcat, you would just write that first word into out right at the beginning (e.g. using strcpy). But you can get the same effect by just making out start out empty. Because "" and "Home" concatenated is the same as just "Home". That help in any way?
    – uliwitness
    Nov 3, 2016 at 13:24
  • The "terminating null byte at the end of dest" that the docs mention is exactly the '\0' the code adds. It won't work without that, because strcat wouldn't know where the string ends, so it wouldn't know where to append the second string.
    – uliwitness
    Nov 3, 2016 at 13:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.