Rae Leng
Rae Leng

Reputation: 65

Trouble understanding indexing array

void addChar() {
    if (lexLen <= 98) {
        lexeme[lexLen++] = nextChar;
        lexeme[lexLen] = 0;
    } else {
        printf("Error - lexeme is too long \n");
    }
}

This is a snippet from a simple lexical analyzer... I'm not sure what the line lexeme[lexLen++] = nextChar; does. And in the next line, why does it assign 0 to lexLen.

It's original comment said its to add nextChar into lexeme, but I don't get how it does that.

Upvotes: 0

Views: 81

Answers (3)

GazTheDestroyer
GazTheDestroyer

Reputation: 21251

Lexeme is an array of characters. Gven the range checks I am going to assume it's 100 characters long and it's already had memory allocated. Your code does not show that.

lexLen is a number. It would appear to be pointing at the end of your string. So if Lexeme currently contains "hello", lexLen will be 5.

lexeme[lexLen++] = nextChar; 

This line does two things. It says "the character at position 5 in lexeme should be set to nextchar. It also increments lexLen (++), so lexLen is now 6.

lexeme[lexLen] = 0;

This says "the character at position 6 in lexeme should be set to 0". This is because strings in C should be null terminated. (0 == null). The null marks the end of the string. The next time AddChar() is called it will be overwritten.

Upvotes: 0

Ok MrJin
Ok MrJin

Reputation: 11

Add nextChar after the original string, then add '\0' at the end, this is a C style string.

At the same time, if the length of string more than 98, print error message

Upvotes: 0

Eric Postpischil
Eric Postpischil

Reputation: 222724

lexeme is an array of char or a pointer to the first char in an array of char.

lexLen is the number of characters currently in the array, before a null character that marks the end of the string being built.

In lexeme[lexLen++] = nextChar;:

  • lexeme[lexLen] (ignore the ++ for the moment) is the element in the array that currently contains the null character marking the end.
  • lexeme[lexLen] = nextChar; changes that element to contain the value in nextChar. Thus, it puts this character from nextChar at the end of the string in the array.
  • The ++ increments lexLen after its value is used for the above.

lexeme[lexLen] = 0; puts a null character in the position after the end of the lengthened string, to mark its new end.

Upvotes: 1

Related Questions