2017-01-30 60 views
-1

我比較字符串的兩個數組,但程序比較一些字符串後異常終止:比較字符串時,下面的程序異常終止?

output of program

什麼是錯我的代碼?

int main() 
{ 

    int N,Q; 
    printf("Enter no. of strings:"); 
    scanf("%d",&N); 
    char *a[N],*b[Q],k[50],*p; 
    int len; 

    //scanning first array of strings 
    for(int i=0;i<N;i++) 
    { 
     scanf("%s",k); 
     len=strlen(k); 
     p=(char*)malloc((len+1)*sizeof(char)); 
     strcpy(p,k); 
     a[i]=p; 
    } 
    printf("no. of Query:"); 
    scanf("%d",&Q); 

    //scanning second array of strings 
    for(int i=0;i<Q;i++) 
    { 
     scanf("%s",k); 
     len=strlen(k); 
     p=(char*)malloc((len+1)*sizeof(char)); 
     strcpy(p,k); 
     b[i]=p; 
    } 

    ***//comparing both the arrays of strings*** 
    for(int i=0;i<Q;i++) 
    { 
     for(int j=0;j<N;j++) 
     { 
      int i=strcmp(a[j],b[i]); 
      printf("%d\t",i); 
     } 
     printf("\n"); 
    } 
    return 0; 
} 
+4

爲什麼這麼多問號? 。 –

+0

'字符* B [Q];'必須的scanf( 「%d」 之後','&Q);我 – BLUEPIXY

+0

輸出attched圖像 –

回答

3

分配STRCMP的結果爲不同的變量名稱,而不是「我」,因爲「我」是你的外循環變量,但我的b[i]是在棧

for(int i=0;i<Q;i++) 
{ 
    for(int j=0;j<N;j++) 
    { 
     int i=strcmp(a[j],b[i]); 
     printf("%d\t",i); 
    } 
    printf("\n"); 
} 
+3

@Clifford''的b i' [I]'不是外可變 – BLUEPIXY

+0

@BLUEPIXY:刪除的評論 - 衛生署。 !代碼有這個問題和其他問題。 – Clifford

3

截至b[Q]Q聲明初始化 - 在此之後可能發生任何事情。您至少需要將b[]的聲明更改爲Q

可能有其他的問題 - 而這僅僅是一個顯而易見的。

1

你正在輸入字符串的數量,而不是正確地使用它。你應該使用動態內存分配。使用的malloc

printf("Enter no. of strings:"); 
scanf("%d",&N); 

char *a[N] 

地方,因爲它應該是

a = malloc(sizeof(char*) * N); 

並返回,以避免內存韭菜之前釋放它。 I am not sure that this is the problem but this can be a step in the right direction.

編輯基於@Clifford評論:C99標準允許這樣,所以如果你的編譯器支持C99,這不是一個問題。

+1

我懷疑這就是問題所在,在C99變長數組(VLA)是有效的。雖然在這個沒有最大檢查用戶輸入的這種情況可能是不明智的。該VLA'b [ Q]'與Q單元化是更大的關注。 – Clifford

+0

同意你@ @ Clifford ... – theadnangondal