【发布时间】:2015-03-16 00:27:27
【问题描述】:
我正在尝试为一个大学项目在 Linux 上使用 lex 和 yacc 构建编译器。
我想通过对树进行深度优先遍历,将包含 char*(其中一些可能为空)的树结构折叠为作为非空 char* 的串联获得的字符串
#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;
}
但是,我得到了这个我无法理解的编译错误:
new.c: In function ‘collapse_branch_rec’:
new.c:36:33: error: lvalue required as left operand of assignment
array++ = n->txt;
这是什么意思?我该如何解决我的问题?
编辑:即使我修复了指针取消引用,我仍然在 libc 中遇到分段错误:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7ab9b2a in strlen () from /usr/lib/libc.so.6
【问题讨论】:
-
if (!size_left) { printf (...); return -1; }递归调用很危险,在这里。 -
collapse_brach() ::
while (p) len += strlen (*p++);中的类似错误 -->while (*p) len += strlen (*p++);[或考虑使用for (p=array; *p; p++) { len += strlen(*p);循环] 2string = str;在末尾collapse_branch() 没用。
标签: c string parsing tree collapse