环境:AMD,win10_x64,cygwin64,vscode,code runner
与预期不符的代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#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
运行结果:
修改符合预期的代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#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
标签:head,乱变,printf,指点,char,tail,str,str2,大佬 From: https://www.cnblogs.com/xuweihui/p/17360278.html