变量乱变问题(已解决)

环境:AMD,win10_x64,cygwin64,vscode,code runner

与预期不符的代码:

#include<string.h>
#include"stdio.h"
typedef char ElemType;
typedef struct BiTNode
{
    ElemType data;
    struct BTNode *lchild;
    struct BTNode *rchild;
} BTNode, *BiTree;
BTNode*CreateBiTree(char *str)
{
    // char str[]="A(B(D,E(H(J,E(L,M(,N)))),C(F,G(,I)))",arr[]="";
    // const char*str=b;
    // char*str=b;
    char*str2;
    int head=strchr(str,'(')-str+1,tail;
    // int head=1,tail=35;
    // for (int i = (int)(strchr(str2,'(')-str2);; i--,str2--)
    // printf("strlen(str)=%d\n",strlen(str));
    str2=str+strlen(str)-1;
    for (int i = strlen(str)-1;; i--,str2--)
    {
        // printf("i=%d,*str2=%c\n",i,*str2);
        if(*str2==')'){
            tail=i;
            printf("tail=%d,i=%d\n",tail,i);
            break;
        }
    }
    // printf("%d(tail)-%d(head)+1-2=%d\n",tail,head,tail-head+1-2);
    str2=str+head;
    char arr[]="";
    char*str3=arr;
    for (int i = 0; i < tail-head+1; i++,str2++,str3++){
        *str3=*str2;
        printf("i=%d, tail=%d, head=%d\n",i,tail,head);
        // printf("%c ",*str3);
    }
    printf("tail=%d head=%d\n",tail,head);
    *str3='\0';
    str3=arr;
    printf("\n%s\n",str3);
    return 0;
}

int main()
{
    BTNode *b = NULL, *p, *lchild = NULL, *rchild = NULL;
    b=CreateBiTree("A(B(D,E(H(J,E(L,M(,N)))),C(F,G(,I)))");
    return 0;
}
View Code

运行结果:

 修改符合预期的代码:

#include<string.h>
#include"stdio.h"
typedef char ElemType;
typedef struct BiTNode
{
    ElemType data;
    struct BTNode *lchild;
    struct BTNode *rchild;
} BTNode, *BiTree;

int main()
{
    BTNode *b = NULL, *p, *lchild = NULL, *rchild = NULL;
    // b=CreateBiTree("A(B(D,E(H(J,E(L,M(,N)))),C(F,G(,I)))");
    char args[]="A(B(D,E(H(J,E(L,M(,N)))),C(F,G(,I)))";
    char*str=args;
    char*str2;
    int head=strchr(str,'(')-str+1,tail;
    // int head=1,tail=35;
    // for (int i = (int)(strchr(str2,'(')-str2);; i--,str2--)
    // printf("strlen(str)=%d\n",strlen(str));
    str2=str+strlen(str)-1;
    for (int i = strlen(str)-1;; i--,str2--)
    {
        // printf("i=%d,*str2=%c\n",i,*str2);
        if(*str2==')'){
            tail=i;
            printf("tail=%d,i=%d\n",tail,i);
            break;
        }
    }
    // printf("%d(tail)-%d(head)+1-2=%d\n",tail,head,tail-head+1-2);
    str2=str+head;
    char arr[]="";
    char*str3=arr;
    for (int i = 0; i < tail-head+1; i++,str2++,str3++){
        *str3=*str2;
        printf("i=%d, tail=%d, head=%d\n",i,tail,head);
        // printf("%c ",*str3);
    }
    printf("tail=%d head=%d\n",tail,head);
    *str3='\0';
    str3=arr;
    printf("\n%s\n",str3);
    return 0;
}
View Code

解决思路:

 

posted @ 2023-04-27 21:30  败人两字非傲即惰  阅读(43)  评论(0编辑  收藏  举报