C 将树折叠为字符串
我正在尝试为一个大学项目在Linux上使用lex&yacc构建一个编译器 我想通过对树进行深度优先遍历,将包含char*(其中一些可能为null)的树结构折叠为一个字符串,该字符串是由非null char*串联而成的C 将树折叠为字符串,c,string,parsing,tree,collapse,C,String,Parsing,Tree,Collapse,我正在尝试为一个大学项目在Linux上使用lex&yacc构建一个编译器 我想通过对树进行深度优先遍历,将包含char*(其中一些可能为null)的树结构折叠为一个字符串,该字符串是由非null char*串联而成的 #include <string.h> #include <stdio.h> #include <stdlib.h> #define MAX_EXPR_LEN 512 struct tnode {
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_EXPR_LEN 512
struct tnode {
char *txt;
struct tnode *child;
struct tnode *next;
};
int collapse_branch_rec (struct tnode *n, char **array, int size_left)
{
if (!n)
return size_left;
if (!size_left)
printf ("an expression is too long to be evaluated; "
"split it into sub-expressions.");
if (n->txt) {
array++ = n->txt;
}
size_left = collapse_branch_rec (n->child, array, --size_left);
return collapse_branch_rec (n->next, array, --size_left);
}
void collapse_branch (struct tnode* root, char *string)
{
char **array = malloc (MAX_EXPR_LEN);
collapse_branch_rec (root, array, MAX_EXPR_LEN);
char **p = array;
int len;
while (p)
len += strlen (*p++);
p = array;
char str[len+1];
while (p)
strcat (str, *p++);
string = str;
}
struct tnode *getnode(char *txt)
{
struct tnode *n = malloc (sizeof (struct tnode));
if (txt)
n->txt = strdup (txt);
return n;
}
int main()
{
char **buffer = malloc (MAX_EXPR_LEN);
struct tnode *a, *b, *c, *d;
a = getnode ("(");
b = getnode (NULL);
c = getnode (")");
d = getnode ("5");
b->child = a;
a->next = d;
d->next = c;
char *string;
collapse_branch (b, string);
printf ("the result is %s", string);
return 0;
}
这是什么意思?我怎样才能解决我的问题呢
编辑:即使我修复了指针解引用,我仍然会在libc中遇到分段错误:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7ab9b2a in strlen () from /usr/lib/libc.so.6
假设
array
指向一个有效的字符指针数组,您可能想取消对指针的引用,访问字符指针并为其分配n->txt
if (n->txt)
{
*array = n->txt;
array++ ;
}
2501年之前的答案将有效。您这样做不起作用的原因是因为array++不再引用array的内存位置,它只是一个数字。例如,您尝试执行(x=3+6)=y,这也行不通,因为(x=3+6)不是指变量x,它只是整数值9
if (n->txt) {
*array = n->txt;
array++;
}
非常感谢。然而,我认为这并不是唯一的错误,。。。代码仍然不起作用。。。请看我的edit@leonixyz您没有将有效字符串传递给strlen。
if(!size_left){printf(…);return-1;}
tru-tu递归调用在这里是危险的。collapse_brach():while(p)len+=strlen(*p++)代码>-->而(*p)len+=strlen(*p++)代码> [或者考虑使用<代码>(p=数组;*p;p++){LeN+= StrLLN(*p);< /COS>循环> 2代码> String=STR;在折叠窗体()的末尾是无用的。
if (n->txt) {
*array = n->txt;
array++;
}