2013-01-04 88 views
2

我正在试验指针和字符串。在下面的代码中,所有的东西都经过测试(你可以自己编译和运行),但是当我试图使用strcmp时,我一直崩溃。该代码在代码块中运行时没有警告。你能指出我的错误,使程序崩溃?比较字符串与strcmp崩溃

#include<stdio.h> 
    #include<stdlib.h> 
    #include<string.h> 

    int main() 
    { 
     int choice,x=7,k,q,cmp,j=0,i=0,N; 
     char v[5],str[80],c[5]; 
     char *B[11][2]= 
     {"-----","0", 
     ".----","1", 
     "..---","2", 
     "...--","3", 
     "....-","4", 
     ".....","5", 
     "-....","6", 
     "--...","7", 
     "---..","8", 
     "----.","9", 
     NULL,NULL}; 

     printf("Give a stream"); 
     if(gets(str)) printf("%s\n",str); 
     fflush(stdin); 
     i=0; 
     while(str[i]) 
     { 
      q=0; 
      j=i+1; 
      while(q%5!=0) 
      { 
       v[j]=str[j]; 
       puts(v); 
       j++; 
       q++; 
      } 
      printf("Hello"); 
      for(k=0; k<11; k++) 
      { 
       strcpy(c,B[k][0]); 
       printf("%s",c); 
       x=strcmp(v,c); 
       //Problem: 
       printf("%d",c); 
       if(x==0) printf("hi"); 
      } 
      i=i+1; 
      j++; 
     } 
    } 
+0

'fflush(stdin);'是未定义的行为。 – chris

+2

这听起来像是学习如何使用调试器的时间... –

+0

这并不一定解决问题,但v [6],c [6]和v [5] = c [5] ='\ 0 “;将是必需的。 –

回答

1

你没有填写v的数据。从q == 0开始,条目while(q%5!=0)在输入时为false。这使得v未初始化,即包含垃圾。

1

你正在做的:

strcpy(c,B[k][0]); 

现在c声明为:

char c[5]; 

B[k][0]有5个字符。既然你想c是一个NUL终止字符数组,你必须有空间来容纳NUL字符,并使用strncpy

+0

C中的数组从0开始。因此,我将0个特征放在0-4中,然后我将在位置5处放置一个NULL。 – alex777

+0

@ alex777:您没有第5个位置,大小为5的数组。 – codaddict

+0

是你是对的!抱歉 – alex777

1

这个程序会在k = 10时转储,因为B [10] [0] = NULL.strcpy(char * dest,const char * src)会在src = null时转储。