0
votes

I was doing an assignment for creating tokens and symbol table for a given input. But there's an Null Reference Exception occurred when handling variables into symbol table. I have searched out the internet but couldn't find the solution. I am a complete newbie in CC. Special thanks to him/her who helps out. The code of specific function where the error is occurring is given below please fix it...

for (int r = 1; r <= SymbolTable.GetLength(0);r++)
{
    //search in the symbol table if variable entry
    //  already exists
    if (SymbolTable[r, 2].Equals(finalArrayc[x].ToString()))
    {
        ind = SymbolTable[r, 1];
        ty = SymbolTable[r, 3];
        val = SymbolTable[r, 4];
        lin = SymbolTable[r, 5];
        tfTokens.AppendText("<var" + ind + ", " + ind + "> ");
        break;
    }
}

The NullReferenceException is on the line:

if (SymbolTable[r, 2].Equals(finalArrayc[x].ToString()))
1
Is the Symbol Table a DataGridView (or extracted from a DGV)? A DGV when editable the last row of the view is a blank line used for adding new data. You may need to ignore the last line if it is null. You can eliminate the line so you do not get the null.jdweng

1 Answers

1
votes

Change to:

if (SymbolTable[r, 2] != null && finalArrayc[x] != null && SymbolTable[r, 2].Equals(finalArrayc[x].ToString()))

One of the two are most probably null at the moment so you need to check before you access.

For the symbol out of bounds exception, you need to also check the lengths of the tables.

i.e.

   SymbolTable[r].Length > 3 &&  SymbolTable[r, 2] != null && finalArrayc.Length < x && finalArrayc[x] != null