【问题标题】:Sorting words runs perfectly locally but gives runtime error online排序单词在本地运行完美,但在线给出运行时错误
【发布时间】:2014-04-07 11:25:02
【问题描述】:

我的单词排序程序已编译并在我的计算机上完美运行,但在线提交时出现运行时错误。它在本地接受输入并提供正确的输出。我无法理解导致此错误的原因。

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

void sort_word(char word[100][10],int n);

int main(){

    int i,n;
    char word[100][10];
    scanf("%d\n",&n);
    for(i=0;i<n;i++){
        scanf("%s",word[i]);
        }
    sort_word(word,n);
    for(i=0;i<n;i++){
        printf("%s\n",word[i]);
        }
return 0;
}

void sort_word(char word[100][10], int n)
{
    int i,j;
    char *tmp,s;
    tmp=&s;
    for(i=0;i<n;i++){
     for(j=0;j<n-1;j++){
        if(strcmp(word[j],word[j+1])>0){
        strcpy(tmp,word[j]);
        strcpy(word[j],word[j+1]);
        strcpy(word[j+1],tmp);
        }
     }
      }
}

【问题讨论】:

  • 我在这里没有遇到任何问题...检查链接...codepad.org/CJCSa7Mi
  • 可能是你输入了长度为 10 或更大的字符串。
  • @someone 我不认识,但那个编程网站仍然给我这个问题。
  • 测试用例的所有字符串都少于 10 个字符。
  • @MayankLal... 你在哪里运行这段代码???

标签: c algorithm sorting


【解决方案1】:
char *tmp,s;
tmp=&s;

这对于你想要达到的目标是错误的。

tmp 将指向一个只有 1 个字符的数组(或者简单地说,指向一个字符)。 你想要的是一个大小为10 的临时缓冲区(这似乎是你为你的单词选择的最大大小)

您可以简单地将其声明为一维数组:char tmp[10]

【讨论】:

    猜你喜欢
    • 2019-05-08
    • 2016-09-03
    • 1970-01-01
    • 2011-10-04
    • 1970-01-01
    • 2011-09-17
    • 2023-03-20
    • 1970-01-01
    • 2019-01-10
    相关资源
    最近更新 更多