【问题标题】:List alphabetically a list in C? [duplicate]按字母顺序列出 C 中的列表? [复制]
【发布时间】:2019-05-08 13:11:15
【问题描述】:

程序收到以下列表:

Google
Apple
Microsoft
Samsung

我想按字母顺序排序。

我编写了以下程序,但运行时出现分段错误。

#include<stdio.h>
#include<string.h>
int main()
{
    char a[20][20],str[20];
    int i;
    FILE *file;
    file=fopen("./test.txt","r");
    if(file == NULL)
        printf("FILE NOT Opened...\n");
    for(i=0;i<5;i++)
    {
        if(fgets(str, 20, file) != NULL)
            {
              strcpy(a[i], str);
              printf("%s",a[i]);
            }
        }
    char *tmp;
    tmp = malloc(20); // still same error
    int j;
    for(i=0; a[i]; i++) {
        for(j = 0; a[j]; j++) {
            if(strcmp(a[i], a[j]) < 0) {
                strcpy(tmp,a[i]);
                strcpy(a[i],a[j]);
                strcpy(a[j],tmp);
            }
        }
    }
    for(i = 0; a[i]; i++) printf("%s\n", a[i]);
        return 0;
}

【问题讨论】:

  • strcpy 需要分配的内存来将字符串复制到目标。变量tmp 未初始化以保存任何内存。
  • 您可以将char str[20] 更改为char tmp[20] 并将其用于输入和排序。
  • 另外,请注意,当您修复 tmp 的内存分配时,循环迭代也是错误的。在像:for(i=0; a[i]; i++) { 这样的行中,for 循环将一直运行,直到 a[i] 为 NULL,这永远不会发生。您可以将循环更改为:for(i=0; i &lt; 5; i++) {,这会有所帮助。其他几个也:您的strcmp &lt; 0 会将您的字符串以相反的顺序排列。 fgets 将在每个字符串的末尾添加一个换行符。你可能不想要那个。
  • 我将 char str[20] 更改为 char tmp[20] 仍然出现分段错误。

标签: c


【解决方案1】:

正如 bruceg 所建议的,您的 for 循环需要工作。而且,您可能想去掉换行符。

另外,记录行数。

我还做了一些进一步的清理工作:

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

#define NLINES  20
#define LWID    20

int
main()
{
    char a[NLINES][LWID];
    char tmp[LWID];
    char *cp;
    int count;
    int i;
    int j;
    FILE *file;

    file = fopen("./test.txt", "r");
    if (file == NULL)
        printf("FILE NOT Opened...\n");

    for (count = 0; count < NLINES; count++) {
        if (fgets(tmp, LWID, file) == NULL)
            break;

        cp = strchr(tmp,'\n');
        if (cp != NULL)
            *cp = 0;

        strcpy(a[count], tmp);
        printf(" %s", a[count]);
    }
    printf("\n");

    fclose(file);

    for (i = 0; i < count; i++) {
        for (j = 0; j < count; j++) {
            if (strcmp(a[i], a[j]) < 0) {
                strcpy(tmp, a[i]);
                strcpy(a[i], a[j]);
                strcpy(a[j], tmp);
            }
        }
    }

    for (i = 0; i < count; i++)
        printf("%s\n", a[i]);

    return 0;
}

这是输出:

 Google Apple Microsoft Samsung
Apple
Google
Microsoft
Samsung

【讨论】:

    猜你喜欢
    • 2014-12-29
    • 2017-05-19
    • 2020-11-24
    • 2020-03-29
    • 1970-01-01
    • 2012-10-21
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多