MST

星途 面试题库

面试题:C语言指针与字符串处理的优化及内存管理

编写一个C程序,从文件中读取多行字符串,每行字符串长度不定。程序需要对这些字符串进行去重操作,将去重后的字符串按长度从短到长输出到另一个文件中。要求使用指针灵活管理内存,避免内存泄漏,并且在处理大规模数据时性能良好。请阐述设计思路,并提供核心代码实现。
27.3万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试

设计思路

  1. 读取文件:使用fgets函数从输入文件逐行读取字符串,注意处理行尾的换行符。
  2. 内存管理:使用动态内存分配mallocrealloc来灵活管理存储字符串的内存,确保内存使用的高效性。
  3. 去重操作:将读取到的字符串存储在一个数组中,每次存储前检查是否已存在,避免重复。
  4. 排序:使用qsort函数对字符串数组按长度进行排序。
  5. 写入文件:将排序后的去重字符串写入输出文件。

核心代码实现

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

#define MAX_LENGTH 1000

// 比较函数,用于qsort按字符串长度排序
int compare(const void *a, const void *b) {
    return strlen(*(char **)a) - strlen(*(char **)b);
}

int main() {
    FILE *inputFile = fopen("input.txt", "r");
    FILE *outputFile = fopen("output.txt", "w");
    if (inputFile == NULL || outputFile == NULL) {
        perror("Failed to open file");
        return 1;
    }

    char **strings = NULL;
    int capacity = 0;
    int count = 0;

    char buffer[MAX_LENGTH];
    while (fgets(buffer, MAX_LENGTH, inputFile) != NULL) {
        // 移除换行符
        buffer[strcspn(buffer, "\n")] = '\0';

        int isDuplicate = 0;
        for (int i = 0; i < count; i++) {
            if (strcmp(strings[i], buffer) == 0) {
                isDuplicate = 1;
                break;
            }
        }

        if (!isDuplicate) {
            if (count >= capacity) {
                capacity = capacity == 0 ? 1 : capacity * 2;
                strings = realloc(strings, capacity * sizeof(char *));
            }
            strings[count] = strdup(buffer);
            count++;
        }
    }

    qsort(strings, count, sizeof(char *), compare);

    for (int i = 0; i < count; i++) {
        fprintf(outputFile, "%s\n", strings[i]);
        free(strings[i]);
    }
    free(strings);

    fclose(inputFile);
    fclose(outputFile);
    return 0;
}