Search code examples
carraysrpn

Where has the first element of my array come from, and what is it?


I am writing a code to produce a C programmed RPN calculator using command line arguments. I am having an issue with the first calculation to be done by the program, as the first element in my array of operators is unknown to me and affects the calculation.

My Command line reads:

$ ./rpn.exe 1 2 3 4 5 + + + +

My array should be {+, +, +, +}

However the output when printed is:

º + + + +

Here is my for loop adding the operators to the array. Operands in my number of Numbers on the cmd line. Is_Op is simply for errors.

for(int c = operands + 1; c < argc; c++)
{
    char b = *argv[c];
    if(Is_Op(b) == 1)
    {
        fprintf(stderr, "%c is not an operator", b);
        return 1;
    }
    else
    {
        operators[c - operands] = b;
    }
}

Here is my array printing function. TotalOps is the total no. of operators. And operators[] is an array of them.

for(int count = 0; count <= TotalOps; count++)
{
    printf("%c ", operators[count]);
}

Solution

  • Have a closer look at

    for(int c = operands + 1; c < argc; c++)
    {
        char b = *argv[c];
        if(Is_Op(b) == 1)
        {
            fprintf(stderr, "%c is not an operator", b);
            return 1;
        }
        else
        {
            operators[c - operands] = b;
        }
    }
    

    since c starts at operands + 1, the first element will be written to operators[c - operands] => operators[1]. So whatever operators[0] initially contains, will stay there.

    You can test this by actually initializing the operators on definition:

    char operators[TotalOps] = { '#' }; // will initialize the first element to '#', all others to '\0'
    

    It should output # + + + + instead of º + + + +.

    So you need to change your code to use the operators array starting with index 0 instead of 1