2014-03-06 91 views
0

我的代码用于输入正则表达式并查找字符串的最小长度。例如:ab*(ab)+因此,要匹配的正则表达式的字符串的最小长度是3.但是我的代码在检查(a|b)时导致问题。它给出了分段错误。但它运行良好(a|b)*正则表达式使用(a | b)

#include <stdio.h> 
#include <stdlib.h> 
#include "queue.h" 

void main() 
{ 
struct node *regexp=null,*language=null; 
char d,lokahead; 
int i,j,k,countl=0,mincount=0,count=0; 
printf("\nEnter the regular expression:"); 
for(i=0;;i++) 
{ 
    scanf("%c",&d); 
    if (d=='.') 
     break; 
    push(&regexp,d); 
} 
//traverse(&regexp); 
mincount=check(&regexp); 
printf("\nThe minimum size of the language should be %d",mincount); 
printf("\nEnter the language:"); 
for(i=0;;i++) 
{ 
    scanf("%c",&d); 
    if (d=='.') 
     break; 
    countl++; 
    push(&language,d); 
} 
} 

---queue.h 

#define null 0 

struct node{ 
     char data; 
     struct node *next; 
     }; 

void push(struct node **head,char d); 
char pop(struct node **head); 

int check(struct node **head) 
{ 
    struct node *k; 
    char d,d1; 
    int count=0,mincount=0; 
    if(*head!=null) 
    { 
     k=*head; 
     while(k!=null) 
     { 
      d=k->data; 
      if ((d>=97 && d<=122) || (d>=65 && d<=90)) 
      { 
       k=k->next; 
       d1=k->data; 
       //printf("\n%c %d",d,mincount); 
       if ((d1>=97 && d1<=122) || (d1>=65 && d1<=90) || (d1=='(') || (d1=='|')) 
        mincount++; 
       /*if (d1=='+') 
       { 
        mincount++; 
        k=k->next; 
       }*/ 
      } 
      else if (d=='*') 
      { 
       k=k->next; 
      } 
      else if (d=='+') 
      { 
       mincount++;    
       k=k->next; 
      } 
      else if (d=='(') //checks for open (
      { 
       k=k->next; 
       while(k->data!=')') //checks till close) 
       { 
        if (k->data!='|') //count the characters inside (...)     
         count++; 
        if ((k->data)=='|')   //counts the case (..a|b..) as 1 character 
         k=k->next; 
        k=k->next;  
       } 
       printf("\nElements inside bracket %d",count); 
       k=k->next;  //proceeds pointer so that we leave (...) 
       if (k->data=='+') //checks if we have (...)+ then the minimum charcters should be the number of char 
        mincount+=count;//inside the() 
       count=0;   
       k=k->next;  //increase the pointer to next element 
      } 
      else if (d=='|') 
      { 
       k=k->next; 
       if (k->data!='+' || k->data!='*' || k->data!='(') 
        mincount++; 
      } 
     } 
    } 
    return mincount; 
} 

输出:

[email protected]:./regex 
Enter the regular expression:ab*(ab)+. 

Elements inside bracket 2 

The minimum size of the language should be 3 

Enter the language:aab. 

输出2:

[email protected]:./regex 
Enter the regular expression:ab*(a|b). 

Segmentation fault.(core dumped) 
+0

我想你需要展示更多的代码 - 创建树的是什么?分配了足够的空间吗? – Floris

+0

是的,我希望如此..但是我不知道为什么它会崩溃,如果没有*或+后()。 – Paku

回答

1

正如其给分割故障代码正在访问其超出范围用于该程序的存储器。检查指针

+0

是的,但问题是()。括号内的任何内容如果没有跟随*或+,则会导致分段错误。 – Paku

+0

给出完整的代码。将尝试从我身边添加更多评论 – user1121210

相关问题