分割故障(核心转储)编程用C

问题描述:

我解决这里给出的HackerRank问题: - https://www.hackerrank.com/challenges/bigger-is-greater分割故障(核心转储)编程用C

程序语句如下:

给定一个词,重新排列的字母来构建另一个词按照字典顺序大于原始词的方式。如果有多个可能的答案,请找到其中的词典中最小的一个。

如果你不明白,那么只要去链接;他们用例子来解释。

我做了下面给出的程序。在这个程序中我做了二维数组。并且变量t决定行数和数量是否修复。

代码正在运行,因为它应该是t = 1。 但是,当t大于1或一些大量它给错误分割错误

代码是如下:

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

int main() { 

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 
    int i,j,n,rot; 
    int t; 
    scanf("%d",&t); 
    char c[t][100]; 
    char temp; 
    for(int i=0;i<t;i++) 
    { 
     scanf(" %s",c[i]); 
    } 
    rot=t; 
    for(int t=0;t<rot;t++) 
    { 
     n = strlen(c[t]); 
     //printf("%d\n",n); 
     for(i=n-1;i>=0;i--) 
     { 
      for(j=i-1;j>=0;j--) 
      { 
       //printf("comparint %c and %c\n",c[t][i],c[t][j]); //FOR DEBUG 
       if(c[t][i]>c[t][j]) goto gotit; 
      } 
     } 
     printf("no answer\n"); 

     continue; 

    gotit: 
     temp = c[t][i]; 
     c[t][i]=c[t][j]; 
     c[t][j]=temp; 
     n = (n-1)-j; 
     //printf("%s\n",c[t]); //FOR DEBUG 
     //printf("%d %d %d\n",i,j,n); //FOR DEBUG 

     for(i=0;i<n-1;i++) 
     { 
      for(int k=0;k<n-1;k++) 
      { 
       // printf("comparint %c and %c\n",c[t][j+k+1],c[t][j+k+2]); 
       if(c[t][j+k+1]>c[t][j+k+2]) 
       { 
        temp = c[t][j+k+1]; 
        c[t][j+k+1]=c[t][j+k+2]; 
        c[t][j+k+2]=temp; 
       } 
      } 
     } 
     printf("%s\n",c[t]); 
    } 

    return 0; 
} 
+1

开始简单 - 解决您的压痕。 –

+0

如果我能解决这个问题,我会直接提交给Hacker Rank,但感谢有机会成为您的代理人。这些网站是关于*你的*能力的。 –

+0

分段故障发生在哪条线上?您应该尝试用调试器逐步执行程序,在各个步骤中检查字符串的值以查看它们何时已经损坏。 – Barmar

t可以是10^5或100,000。您的c数组为c[t][100],因此其大小为100000 * 100,即10,000,000。你可能会遇到堆栈溢出。

正如WhozCraig指出的那样,每个案件的处理都是独立的。因此,c可以是一维数组:char c[100]。将所有c[t][...]更改为c[...]

调整的东西,让你有一个外循环:

int 
main() 
{ 
    int t; 
    char c[100]; 

    scanf("%d", &t); 

    for (int i = 0; i < t; i++) { 
     scanf(" %s", c); 
     // do all processing for this line ... 
     n = strlen(c); 
    } 

    return 0; 
}