在C中使用malloc

问题描述

星星


给出一个名为testdata.in的文件,根据星数以升序打印所有星 每行。

格式输入

输入内容包含N行要排序的星星。

格式化输出

根据每行的星数以升序打印星。

约束

testdata.in中的N行数未指定。但是,可以保证数据不会超出给定的内存限制。

样本输入(testdata.in)

**********
****
******
*****
*********
********
*******
************
***********
*
***
**

示例输出

*
**
***
****
*****
******
*******
********
*********
**********
***********
************

这是我编写的代码。我想在此代码中使用malloc,但我想知道如何

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

char star[40000][40000],temp[10][40000];

int main() {
    FILE *fp = fopen("testdata.in","r");
    int count = 0; 
    while (fscanf(fp,"%s\n",&star[count]) == 1) {
        count++;
    }
    for (int i = 0; i < count; i++) {
        for (int j = 0; j < count; j++) {
            if (strcmp(star[i],star[j]) < 0) {
                strcpy(temp[0],star[i]);
                strcpy(star[i],star[j]);
                strcpy(star[j],temp[0]);
            }
        }
    }
    for (int i = 0; i < count; i++) {
        printf("%s\n",star[i]);
    }
    count = 0;
    fclose(fp);
    return 0;
}

解决方法

为什么要烦恼存储行?整个文本都是星星,所以最简单的方法是保存某种直方图:1星线的数量,2星线的数量...... p

所以本质上是一个数组

#define MAX_STARS_PER_LINE 40000
uint32_t counts[MAX_STARS_PER_LINE+1] = {0};

/* pseudocode:
  while not eof:
    line = getline  (without line ending character)
    stars = length(line)
    counts[stars]++;
 */

读取文件后,只需遍历此数组,并为每个条目i打印counts[i]i星。

当然,您可以采用另一种方法,使每行都保留一个带有条目的数组,但是每行只有一个数字就足够了。那当然要对数组进行排序

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...