问题
I am trying to add =
at the end of my array and then end it by appending a 0
This is how I allocate my space
char* postExpr = malloc(sizeof(char)*MAX_LEN);
I have tried many methods but I am still failing to append character '=' at the end of my string, every other character works just fine.
What have I tried
postExpr[postLen++] = 61;
postExpr[postLen++] = '=';
postExpr[postLen++] = infExpr[i];
in infExpr[i] is stored the value '='
EDIT:
char* infix2postfix (const char* infExpr) {
char* postExpr = malloc (sizeof(char)*MAX_LEN);
if(postExpr == NULL)
return NULL;
tStack* s = (tStack*) malloc(sizeof(tStack));
if(s == NULL)
{
free(postExpr);
return NULL;
}
unsigned postLen = 0;
for(int i = 0; i< MAX_LEN; i++)
{
switch(infExpr[i])
{
case '*':
case '/':
case '+':
case '-': doOperation(s,infExpr[i],postExpr,&postLen); break;
case '(': stackPush(s,infExpr[i]); break;
case ')': untilLeftPar(s,postExpr,&postLen); break;
case '=':
while(!stackEmpty(s))
{
stackTop(s,&postExpr[postLen++]);
stackPop(s);
}
postExpr[postLen++] = '='; //NO APPEND HERE!!!
postExpr[postLen++] = 0;
postLen = MAX_LEN;
break;
case 0:
postExpr[postLen++] = '=';
postExpr[postLen++] = 0;
postLen = MAX_LEN;
break;
default: postExpr[postLen++] = infExpr[i]; break;
}
}
return postExpr;
}
回答1:
In your code you are adding =
probably after 0
which is previously present there.So,
postExpr[postLen++] = '=';
postExpr[postLen++] = 0;
should be
postExpr[postLen-1] = '=';
postExpr[postLen++] = 0;
Or there would be NULL
terminator in your string before.
回答2:
The problem was with my stack, I forgot to initializate it, so it would store value 0 which was appended before '=' and thus made the char unreadable
回答3:
It seems to me that you're passing the address of postLen
to a lot of different subroutines.
And then you're complaining that a simple assignment of a character in an array, indexed by the variable you were passing around is not working.
My advice would be to do two things:
First, in the
case '=':
part of your code, print out thepostLen
and also thestrlen(postExpr)
to check if they are in sync.Second, start looking into your various subroutines to see if you can determine where the
postLen
value is going wrong.
来源:https://stackoverflow.com/questions/46715642/how-to-append-to-a-string