Home > Software engineering >  value over written in the array during loop
value over written in the array during loop

Time:10-17

I am currently trying to convert an equation into simpler form and found out that my codes are over writing the value at the end of the loop.

I have found out similar discussions but not exactly what I am looking for. Most of articles were using other languages so I couldn't get the answer.

Any answers are appreciated and thanks in advance.

followings are my code

int index = 0;
int result = 0;
char tresult[100];
char *equation[100] = { NULL, };
char *temp = strtok(input, " ");

for(int i = 1; i < x; i = i   2)
{
    char *temp_sign = equation[i];
    
    if(*temp_sign == '*')
    {
        result = atoi(equation[i - 1]) * atoi(equation[i  1]);
        sprintf(tresult, "%d", result);
        equation[i - 1] = tresult;
        sprintf(equation[i], "%d", 0);
        sprintf(equation[i   1], "%d", 0);
    }
}

for(int j = 0; j < x; j  )
{
    printf("%s ", equation[j]);
}

Expected input

5 * 3   1 * 2

targeted output

15 0 0   2 0 0

I will remove 0 by adding extra codes to make it as

15   2

but currently, my output looks like

2 0 0   2 0 0

When I print out the value in the loop, all the values were correctly shown. What may be the cause of such problem?

CodePudding user response:

It might be easier to understand if we draw out the pointer instead.

Assuming that input is initially equal to "5 * 3 1 * 2", then after the loop equation will look something like this:

 ------------- 
| equation[0] | ------------------------\
 -------------                          |
| equation[1] | --> | input[2] | ... |  |      ------------ ----- 
 -------------                           >--> | tresult[0] | ... |
| equation[2] | --> | input[4] | ... |  |      ------------ ----- 
 -------------                          |
| equation[3] | ------------------------/
 ------------- 
| equation[4] | --> | input[10] | ... |
 ------------- 
| equation[5] | --> | input[12] | ... |
 ------------- 

As seen in the above "drawing" both equation[0] and equation[3] will be pointing to the first character of the single array tresult.

And tresult will always contain the contents last written into it with sprintf(tresult, "%d", result). Which in your example will be "2".

  •  Tags:  
  • c
  • Related