How to append '=' to a string

ぐ巨炮叔叔 提交于 2021-01-27 19:11:51

问题


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:

  1. First, in the case '=': part of your code, print out the postLen and also the strlen(postExpr) to check if they are in sync.

  2. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!